imgui_impl_glfw.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. // ImGui GLFW binding with OpenGL
  2. // In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
  3. // If your context or own usage of OpenGL involve anything GL3/GL4, prefer using the code in opengl3_example.
  4. // If you are not sure what that means, prefer using the code in opengl3_example.
  5. // You *might* use this code with a GL3/GL4 context but make sure you disable the programmable pipeline by calling "glUseProgram(0)" before ImGui::Render().
  6. // We cannot do that from GL2 code because the function doesn't exist. Mixing GL2 calls and GL3/GL4 calls is giving trouble to many librairies/drivers.
  7. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
  8. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
  9. // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
  10. // https://github.com/ocornut/imgui
  11. #include <imgui.h>
  12. #include "imgui_impl_glfw.h"
  13. // GLFW
  14. #include <GLFW/glfw3.h>
  15. #ifdef _WIN32
  16. #undef APIENTRY
  17. #define GLFW_EXPOSE_NATIVE_WIN32
  18. #define GLFW_EXPOSE_NATIVE_WGL
  19. #include <GLFW/glfw3native.h>
  20. #endif
  21. // Data
  22. static GLFWwindow* g_Window = NULL;
  23. static double g_Time = 0.0f;
  24. static bool g_MousePressed[3] = { false, false, false };
  25. static float g_MouseWheel = 0.0f;
  26. static GLuint g_FontTexture = 0;
  27. // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
  28. void ImGui_ImplGlfwGL2_RenderDrawLists(ImDrawData* draw_data)
  29. // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so.
  30. // If text or lines are blurry when integrating ImGui in your engine: in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
  31. {
  32. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  33. ImGuiIO& io = ImGui::GetIO();
  34. int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
  35. int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
  36. if (fb_width == 0 || fb_height == 0)
  37. return;
  38. draw_data->ScaleClipRects(io.DisplayFramebufferScale);
  39. // We are using the OpenGL fixed pipeline to make the example code simpler to read!
  40. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers, polygon fill.
  41. GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  42. GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
  43. GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
  44. GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
  45. glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
  46. glEnable(GL_BLEND);
  47. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  48. glDisable(GL_CULL_FACE);
  49. glDisable(GL_DEPTH_TEST);
  50. glEnable(GL_SCISSOR_TEST);
  51. glEnableClientState(GL_VERTEX_ARRAY);
  52. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  53. glEnableClientState(GL_COLOR_ARRAY);
  54. glEnable(GL_TEXTURE_2D);
  55. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  56. //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context where shaders may be bound
  57. // Setup viewport, orthographic projection matrix
  58. glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
  59. glMatrixMode(GL_PROJECTION);
  60. glPushMatrix();
  61. glLoadIdentity();
  62. glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f);
  63. glMatrixMode(GL_MODELVIEW);
  64. glPushMatrix();
  65. glLoadIdentity();
  66. // Render command lists
  67. #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
  68. for (int n = 0; n < draw_data->CmdListsCount; n++)
  69. {
  70. const ImDrawList* cmd_list = draw_data->CmdLists[n];
  71. const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
  72. const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
  73. glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, pos)));
  74. glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, uv)));
  75. glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, col)));
  76. for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
  77. {
  78. const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
  79. if (pcmd->UserCallback)
  80. {
  81. pcmd->UserCallback(cmd_list, pcmd);
  82. }
  83. else
  84. {
  85. glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
  86. glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
  87. glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer);
  88. }
  89. idx_buffer += pcmd->ElemCount;
  90. }
  91. }
  92. #undef OFFSETOF
  93. // Restore modified state
  94. glDisableClientState(GL_COLOR_ARRAY);
  95. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  96. glDisableClientState(GL_VERTEX_ARRAY);
  97. glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture);
  98. glMatrixMode(GL_MODELVIEW);
  99. glPopMatrix();
  100. glMatrixMode(GL_PROJECTION);
  101. glPopMatrix();
  102. glPopAttrib();
  103. glPolygonMode(GL_FRONT, last_polygon_mode[0]); glPolygonMode(GL_BACK, last_polygon_mode[1]);
  104. glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
  105. glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
  106. }
  107. static const char* ImGui_ImplGlfwGL2_GetClipboardText(void* user_data)
  108. {
  109. return glfwGetClipboardString((GLFWwindow*)user_data);
  110. }
  111. static void ImGui_ImplGlfwGL2_SetClipboardText(void* user_data, const char* text)
  112. {
  113. glfwSetClipboardString((GLFWwindow*)user_data, text);
  114. }
  115. void ImGui_ImplGlfwGL2_MouseButtonCallback(GLFWwindow*, int button, int action, int /*mods*/)
  116. {
  117. if (action == GLFW_PRESS && button >= 0 && button < 3)
  118. g_MousePressed[button] = true;
  119. }
  120. void ImGui_ImplGlfwGL2_ScrollCallback(GLFWwindow*, double /*xoffset*/, double yoffset)
  121. {
  122. g_MouseWheel += (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines.
  123. }
  124. void ImGui_ImplGlfwGL2_KeyCallback(GLFWwindow*, int key, int, 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. (void)mods; // Modifiers are not reliable across systems
  132. io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL];
  133. io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT];
  134. io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT];
  135. io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER];
  136. }
  137. void ImGui_ImplGlfwGL2_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. bool ImGui_ImplGlfwGL2_CreateDeviceObjects()
  144. {
  145. // Build texture atlas
  146. ImGuiIO& io = ImGui::GetIO();
  147. unsigned char* pixels;
  148. int width, height;
  149. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.
  150. // Upload texture to graphics system
  151. GLint last_texture;
  152. glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  153. glGenTextures(1, &g_FontTexture);
  154. glBindTexture(GL_TEXTURE_2D, g_FontTexture);
  155. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  156. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  157. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  158. // Store our identifier
  159. io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
  160. // Restore state
  161. glBindTexture(GL_TEXTURE_2D, last_texture);
  162. return true;
  163. }
  164. void ImGui_ImplGlfwGL2_InvalidateDeviceObjects()
  165. {
  166. if (g_FontTexture)
  167. {
  168. glDeleteTextures(1, &g_FontTexture);
  169. ImGui::GetIO().Fonts->TexID = 0;
  170. g_FontTexture = 0;
  171. }
  172. }
  173. bool ImGui_ImplGlfwGL2_Init(GLFWwindow* window, bool install_callbacks)
  174. {
  175. g_Window = window;
  176. ImGuiIO& io = ImGui::GetIO();
  177. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
  178. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  179. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  180. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  181. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  182. io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;
  183. io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
  184. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  185. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  186. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  187. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  188. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  189. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  190. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  191. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  192. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  193. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  194. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  195. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  196. io.RenderDrawListsFn = ImGui_ImplGlfwGL2_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
  197. io.SetClipboardTextFn = ImGui_ImplGlfwGL2_SetClipboardText;
  198. io.GetClipboardTextFn = ImGui_ImplGlfwGL2_GetClipboardText;
  199. io.ClipboardUserData = g_Window;
  200. #ifdef _WIN32
  201. io.ImeWindowHandle = glfwGetWin32Window(g_Window);
  202. #endif
  203. if (install_callbacks)
  204. {
  205. glfwSetMouseButtonCallback(window, ImGui_ImplGlfwGL2_MouseButtonCallback);
  206. glfwSetScrollCallback(window, ImGui_ImplGlfwGL2_ScrollCallback);
  207. glfwSetKeyCallback(window, ImGui_ImplGlfwGL2_KeyCallback);
  208. glfwSetCharCallback(window, ImGui_ImplGlfwGL2_CharCallback);
  209. }
  210. return true;
  211. }
  212. void ImGui_ImplGlfwGL2_Shutdown()
  213. {
  214. ImGui_ImplGlfwGL2_InvalidateDeviceObjects();
  215. ImGui::Shutdown();
  216. }
  217. void ImGui_ImplGlfwGL2_NewFrame()
  218. {
  219. if (!g_FontTexture)
  220. ImGui_ImplGlfwGL2_CreateDeviceObjects();
  221. ImGuiIO& io = ImGui::GetIO();
  222. // Setup display size (every frame to accommodate for window resizing)
  223. int w, h;
  224. int display_w, display_h;
  225. glfwGetWindowSize(g_Window, &w, &h);
  226. glfwGetFramebufferSize(g_Window, &display_w, &display_h);
  227. io.DisplaySize = ImVec2((float)w, (float)h);
  228. io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0);
  229. // Setup time step
  230. double current_time = glfwGetTime();
  231. io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
  232. g_Time = current_time;
  233. // Setup inputs
  234. // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
  235. if (glfwGetWindowAttrib(g_Window, GLFW_FOCUSED))
  236. {
  237. if (io.WantMoveMouse)
  238. {
  239. glfwSetCursorPos(g_Window, (double)io.MousePos.x, (double)io.MousePos.y); // Set mouse position if requested by io.WantMoveMouse flag (used when io.NavMovesTrue is enabled by user and using directional navigation)
  240. }
  241. else
  242. {
  243. double mouse_x, mouse_y;
  244. glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
  245. io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Get mouse position in screen coordinates (set to -1,-1 if no mouse / on another screen, etc.)
  246. }
  247. }
  248. else
  249. {
  250. io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX);
  251. }
  252. for (int i = 0; i < 3; i++)
  253. {
  254. 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.
  255. g_MousePressed[i] = false;
  256. }
  257. io.MouseWheel = g_MouseWheel;
  258. g_MouseWheel = 0.0f;
  259. // Hide OS mouse cursor if ImGui is drawing it
  260. glfwSetInputMode(g_Window, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL);
  261. // Start the frame
  262. ImGui::NewFrame();
  263. }