imgui_impl_glfw_gl3.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. // ImGui GLFW binding with OpenGL3 + shaders
  2. // https://github.com/ocornut/imgui
  3. #include <imgui.h>
  4. #include "imgui_impl_glfw_gl3.h"
  5. // GL3W/GLFW
  6. #include <GL/gl3w.h>
  7. #include <GLFW/glfw3.h>
  8. #ifdef _MSC_VER
  9. #undef APIENTRY
  10. #define GLFW_EXPOSE_NATIVE_WIN32
  11. #define GLFW_EXPOSE_NATIVE_WGL
  12. #include <GLFW/glfw3native.h>
  13. #endif
  14. // Data
  15. static GLFWwindow* g_Window = NULL;
  16. static double g_Time = 0.0f;
  17. static bool g_MousePressed[3] = { false, false, false };
  18. static float g_MouseWheel = 0.0f;
  19. static GLuint g_FontTexture = 0;
  20. static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
  21. static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0;
  22. static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_AttribLocationColor = 0;
  23. static size_t g_VboSize = 0;
  24. static unsigned int g_VboHandle = 0, g_VaoHandle = 0;
  25. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  26. // If text or lines are blurry when integrating ImGui in your engine:
  27. // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  28. static void ImGui_ImplGlfwGL3_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. GLint last_program, last_texture;
  34. glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
  35. glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  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(g_ShaderHandle);
  54. glUniform1i(g_AttribLocationTex, 0);
  55. glUniformMatrix4fv(g_AttribLocationProjMtx, 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, g_VboHandle);
  61. size_t needed_vtx_size = total_vtx_count * sizeof(ImDrawVert);
  62. if (g_VboSize < needed_vtx_size)
  63. {
  64. g_VboSize = needed_vtx_size + 5000 * sizeof(ImDrawVert); // Grow buffer
  65. glBufferData(GL_ARRAY_BUFFER, g_VboSize, NULL, GL_STREAM_DRAW);
  66. }
  67. // Copy and convert all vertices into a single contiguous buffer
  68. unsigned char* vtx_data = (unsigned char*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
  69. if (!vtx_data)
  70. return;
  71. for (int n = 0; n < cmd_lists_count; n++)
  72. {
  73. const ImDrawList* cmd_list = cmd_lists[n];
  74. memcpy(vtx_data, &cmd_list->vtx_buffer[0], cmd_list->vtx_buffer.size() * sizeof(ImDrawVert));
  75. vtx_data += cmd_list->vtx_buffer.size() * sizeof(ImDrawVert);
  76. }
  77. glUnmapBuffer(GL_ARRAY_BUFFER);
  78. glBindBuffer(GL_ARRAY_BUFFER, 0);
  79. glBindVertexArray(g_VaoHandle);
  80. int vtx_offset = 0;
  81. for (int n = 0; n < cmd_lists_count; n++)
  82. {
  83. const ImDrawList* cmd_list = cmd_lists[n];
  84. const ImDrawIdx* idx_buffer = (const unsigned short*)&cmd_list->idx_buffer.front();
  85. const ImDrawCmd* pcmd_end = cmd_list->commands.end();
  86. for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++)
  87. {
  88. if (pcmd->user_callback)
  89. {
  90. pcmd->user_callback(cmd_list, pcmd);
  91. }
  92. else
  93. {
  94. glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->texture_id);
  95. 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));
  96. glDrawElementsBaseVertex(GL_TRIANGLES, pcmd->idx_count, GL_UNSIGNED_SHORT, idx_buffer, vtx_offset);
  97. }
  98. idx_buffer += pcmd->idx_count;
  99. }
  100. vtx_offset += (int)cmd_list->vtx_buffer.size();
  101. }
  102. // Restore modified state
  103. glBindVertexArray(0);
  104. glUseProgram(last_program);
  105. glDisable(GL_SCISSOR_TEST);
  106. glBindTexture(GL_TEXTURE_2D, last_texture);
  107. }
  108. static const char* ImGui_ImplGlfwGL3_GetClipboardText()
  109. {
  110. return glfwGetClipboardString(g_Window);
  111. }
  112. static void ImGui_ImplGlfwGL3_SetClipboardText(const char* text)
  113. {
  114. glfwSetClipboardString(g_Window, text);
  115. }
  116. void ImGui_ImplGlfwGL3_MouseButtonCallback(GLFWwindow*, int button, int action, int /*mods*/)
  117. {
  118. if (action == GLFW_PRESS && button >= 0 && button < 3)
  119. g_MousePressed[button] = true;
  120. }
  121. void ImGui_ImplGlfwGL3_ScrollCallback(GLFWwindow*, double /*xoffset*/, double yoffset)
  122. {
  123. g_MouseWheel += (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines.
  124. }
  125. void ImGui_ImplGlfwGL3_KeyCallback(GLFWwindow*, int key, int, int action, int mods)
  126. {
  127. ImGuiIO& io = ImGui::GetIO();
  128. if (action == GLFW_PRESS)
  129. io.KeysDown[key] = true;
  130. if (action == GLFW_RELEASE)
  131. io.KeysDown[key] = false;
  132. (void)mods; // Modifiers are not reliable across systems
  133. io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL];
  134. io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT];
  135. io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT];
  136. }
  137. void ImGui_ImplGlfwGL3_CharCallback(GLFWwindow*, unsigned int c)
  138. {
  139. ImGuiIO& io = ImGui::GetIO();
  140. if (c > 0 && c < 0x10000)
  141. io.AddInputCharacter((unsigned short)c);
  142. }
  143. void ImGui_ImplGlfwGL3_CreateFontsTexture()
  144. {
  145. ImGuiIO& io = ImGui::GetIO();
  146. unsigned char* pixels;
  147. int width, height;
  148. 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.
  149. glGenTextures(1, &g_FontTexture);
  150. glBindTexture(GL_TEXTURE_2D, g_FontTexture);
  151. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  152. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  153. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  154. // Store our identifier
  155. io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
  156. // Cleanup (don't clear the input data if you want to append new fonts later)
  157. io.Fonts->ClearInputData();
  158. io.Fonts->ClearTexData();
  159. }
  160. bool ImGui_ImplGlfwGL3_CreateDeviceObjects()
  161. {
  162. const GLchar *vertex_shader =
  163. "#version 330\n"
  164. "uniform mat4 ProjMtx;\n"
  165. "in vec2 Position;\n"
  166. "in vec2 UV;\n"
  167. "in vec4 Color;\n"
  168. "out vec2 Frag_UV;\n"
  169. "out vec4 Frag_Color;\n"
  170. "void main()\n"
  171. "{\n"
  172. " Frag_UV = UV;\n"
  173. " Frag_Color = Color;\n"
  174. " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
  175. "}\n";
  176. const GLchar* fragment_shader =
  177. "#version 330\n"
  178. "uniform sampler2D Texture;\n"
  179. "in vec2 Frag_UV;\n"
  180. "in vec4 Frag_Color;\n"
  181. "out vec4 Out_Color;\n"
  182. "void main()\n"
  183. "{\n"
  184. " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n"
  185. "}\n";
  186. g_ShaderHandle = glCreateProgram();
  187. g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
  188. g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
  189. glShaderSource(g_VertHandle, 1, &vertex_shader, 0);
  190. glShaderSource(g_FragHandle, 1, &fragment_shader, 0);
  191. glCompileShader(g_VertHandle);
  192. glCompileShader(g_FragHandle);
  193. glAttachShader(g_ShaderHandle, g_VertHandle);
  194. glAttachShader(g_ShaderHandle, g_FragHandle);
  195. glLinkProgram(g_ShaderHandle);
  196. g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
  197. g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
  198. g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position");
  199. g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV");
  200. g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color");
  201. glGenBuffers(1, &g_VboHandle);
  202. glGenVertexArrays(1, &g_VaoHandle);
  203. glBindVertexArray(g_VaoHandle);
  204. glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
  205. glEnableVertexAttribArray(g_AttribLocationPosition);
  206. glEnableVertexAttribArray(g_AttribLocationUV);
  207. glEnableVertexAttribArray(g_AttribLocationColor);
  208. #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
  209. glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
  210. glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
  211. glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
  212. #undef OFFSETOF
  213. glBindVertexArray(0);
  214. glBindBuffer(GL_ARRAY_BUFFER, 0);
  215. ImGui_ImplGlfwGL3_CreateFontsTexture();
  216. return true;
  217. }
  218. bool ImGui_ImplGlfwGL3_Init(GLFWwindow* window, bool install_callbacks)
  219. {
  220. g_Window = window;
  221. ImGuiIO& io = ImGui::GetIO();
  222. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  223. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  224. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  225. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  226. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  227. io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;
  228. io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
  229. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  230. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  231. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  232. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  233. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  234. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  235. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  236. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  237. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  238. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  239. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  240. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  241. io.RenderDrawListsFn = ImGui_ImplGlfwGL3_RenderDrawLists;
  242. io.SetClipboardTextFn = ImGui_ImplGlfwGL3_SetClipboardText;
  243. io.GetClipboardTextFn = ImGui_ImplGlfwGL3_GetClipboardText;
  244. #ifdef _MSC_VER
  245. io.ImeWindowHandle = glfwGetWin32Window(g_Window);
  246. #endif
  247. if (install_callbacks)
  248. {
  249. glfwSetMouseButtonCallback(window, ImGui_ImplGlfwGL3_MouseButtonCallback);
  250. glfwSetScrollCallback(window, ImGui_ImplGlfwGL3_ScrollCallback);
  251. glfwSetKeyCallback(window, ImGui_ImplGlfwGL3_KeyCallback);
  252. glfwSetCharCallback(window, ImGui_ImplGlfwGL3_CharCallback);
  253. }
  254. return true;
  255. }
  256. void ImGui_ImplGlfwGL3_Shutdown()
  257. {
  258. if (g_VaoHandle) glDeleteVertexArrays(1, &g_VaoHandle);
  259. if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle);
  260. g_VaoHandle = 0;
  261. g_VboHandle = 0;
  262. glDetachShader(g_ShaderHandle, g_VertHandle);
  263. glDeleteShader(g_VertHandle);
  264. g_VertHandle = 0;
  265. glDetachShader(g_ShaderHandle, g_FragHandle);
  266. glDeleteShader(g_FragHandle);
  267. g_FragHandle = 0;
  268. glDeleteProgram(g_ShaderHandle);
  269. g_ShaderHandle = 0;
  270. if (g_FontTexture)
  271. {
  272. glDeleteTextures(1, &g_FontTexture);
  273. ImGui::GetIO().Fonts->TexID = 0;
  274. g_FontTexture = 0;
  275. }
  276. ImGui::Shutdown();
  277. }
  278. void ImGui_ImplGlfwGL3_NewFrame()
  279. {
  280. if (!g_FontTexture)
  281. ImGui_ImplGlfwGL3_CreateDeviceObjects();
  282. ImGuiIO& io = ImGui::GetIO();
  283. // Setup display size (every frame to accommodate for window resizing)
  284. int w, h;
  285. int display_w, display_h;
  286. glfwGetWindowSize(g_Window, &w, &h);
  287. glfwGetFramebufferSize(g_Window, &display_w, &display_h);
  288. io.DisplaySize = ImVec2((float)display_w, (float)display_h);
  289. // Setup time step
  290. double current_time = glfwGetTime();
  291. io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
  292. g_Time = current_time;
  293. // Setup inputs
  294. // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
  295. if (glfwGetWindowAttrib(g_Window, GLFW_FOCUSED))
  296. {
  297. double mouse_x, mouse_y;
  298. glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
  299. mouse_x *= (float)display_w / w; // Convert mouse coordinates to pixels
  300. mouse_y *= (float)display_h / h;
  301. io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
  302. }
  303. else
  304. {
  305. io.MousePos = ImVec2(-1,-1);
  306. }
  307. for (int i = 0; i < 3; i++)
  308. {
  309. io.MouseDown[i] = g_MousePressed[i] || glfwGetMouseButton(g_Window, i) != 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.
  310. g_MousePressed[i] = false;
  311. }
  312. io.MouseWheel = g_MouseWheel;
  313. g_MouseWheel = 0.0f;
  314. // Hide OS mouse cursor if ImGui is drawing it
  315. glfwSetInputMode(g_Window, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL);
  316. // Start the frame
  317. ImGui::NewFrame();
  318. }