main.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. #define GLEW_STATIC
  2. #include <GL/glew.h>
  3. #include <GLFW/glfw3.h>
  4. #define STB_IMAGE_IMPLEMENTATION
  5. #include "stb_image.h" // for .png loading
  6. #include "../../imgui.h"
  7. #ifdef _MSC_VER
  8. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  9. #endif
  10. static GLFWwindow* window;
  11. static GLuint vbo;
  12. static GLuint vao;
  13. static GLuint vertexShader;
  14. static GLuint fragmentShader;
  15. static GLuint shaderProgram;
  16. static GLuint fontTex;
  17. static GLint uniMVP;
  18. static GLint uniClipRect;
  19. static void ImImpl_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
  20. {
  21. size_t total_vtx_count = 0;
  22. for (int n = 0; n < cmd_lists_count; n++)
  23. total_vtx_count += cmd_lists[n]->vtx_buffer.size();
  24. if (total_vtx_count == 0)
  25. return;
  26. int read_pos_clip_rect_buf = 0; // offset in 'clip_rect_buffer'. each PushClipRect command consume 1 of those.
  27. ImVector<ImVec4> clip_rect_stack;
  28. clip_rect_stack.push_back(ImVec4(-9999,-9999,+9999,+9999));
  29. // Setup orthographic projection
  30. const float L = 0.0f;
  31. const float R = ImGui::GetIO().DisplaySize.x;
  32. const float B = ImGui::GetIO().DisplaySize.y;
  33. const float T = 0.0f;
  34. const float mvp[4][4] =
  35. {
  36. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  37. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  38. { 0.0f, 0.0f, -1.0f, 0.0f },
  39. { -(R+L)/(R-L), -(T+B)/(T-B), 0.0f, 1.0f },
  40. };
  41. glBindBuffer(GL_ARRAY_BUFFER, vbo);
  42. glBindVertexArray(vao);
  43. glBufferData(GL_ARRAY_BUFFER, total_vtx_count * sizeof(ImDrawVert), NULL, GL_STREAM_DRAW);
  44. unsigned char* buffer_data = (unsigned char*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
  45. if (!buffer_data)
  46. return;
  47. int vtx_consumed = 0;
  48. for (int n = 0; n < cmd_lists_count; n++)
  49. {
  50. const ImDrawList* cmd_list = cmd_lists[n];
  51. if (!cmd_list->vtx_buffer.empty())
  52. {
  53. memcpy(buffer_data, &cmd_list->vtx_buffer[0], cmd_list->vtx_buffer.size() * sizeof(ImDrawVert));
  54. buffer_data += cmd_list->vtx_buffer.size() * sizeof(ImDrawVert);
  55. vtx_consumed += cmd_list->vtx_buffer.size();
  56. }
  57. }
  58. glUnmapBuffer(GL_ARRAY_BUFFER);
  59. glUseProgram(shaderProgram);
  60. glUniformMatrix4fv(uniMVP, 1, GL_FALSE, &mvp[0][0]);
  61. // Setup render state: alpha-blending enabled, no face culling, no depth testing
  62. glEnable(GL_BLEND);
  63. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  64. glDisable(GL_CULL_FACE);
  65. glDisable(GL_DEPTH_TEST);
  66. glBindTexture(GL_TEXTURE_2D, fontTex);
  67. vtx_consumed = 0; // offset in vertex buffer. each command consume ImDrawCmd::vtx_count of those
  68. bool clip_rect_dirty = true;
  69. for (int n = 0; n < cmd_lists_count; n++)
  70. {
  71. const ImDrawList* cmd_list = cmd_lists[n];
  72. if (cmd_list->commands.empty() || cmd_list->vtx_buffer.empty())
  73. continue;
  74. const ImDrawCmd* pcmd = &cmd_list->commands.front();
  75. const ImDrawCmd* pcmd_end = &cmd_list->commands.back();
  76. int clip_rect_buf_consumed = 0; // offset in cmd_list->clip_rect_buffer. each PushClipRect command consume 1 of those.
  77. while (pcmd <= pcmd_end)
  78. {
  79. const ImDrawCmd& cmd = *pcmd++;
  80. switch (cmd.cmd_type)
  81. {
  82. case ImDrawCmdType_DrawTriangleList:
  83. if (clip_rect_dirty)
  84. {
  85. glUniform4fv(uniClipRect, 1, (float*)&clip_rect_stack.back());
  86. clip_rect_dirty = false;
  87. }
  88. glDrawArrays(GL_TRIANGLES, vtx_consumed, cmd.vtx_count);
  89. vtx_consumed += cmd.vtx_count;
  90. break;
  91. case ImDrawCmdType_PushClipRect:
  92. clip_rect_stack.push_back(cmd_list->clip_rect_buffer[clip_rect_buf_consumed++]);
  93. clip_rect_dirty = true;
  94. break;
  95. case ImDrawCmdType_PopClipRect:
  96. clip_rect_stack.pop_back();
  97. clip_rect_dirty = true;
  98. break;
  99. }
  100. }
  101. }
  102. }
  103. static const char* ImImpl_GetClipboardTextFn()
  104. {
  105. return glfwGetClipboardString(window);
  106. }
  107. static void ImImpl_SetClipboardTextFn(const char* text, const char* text_end)
  108. {
  109. if (!text_end)
  110. text_end = text + strlen(text);
  111. char* buf = (char*)malloc(text_end - text + 1);
  112. memcpy(buf, text, text_end-text);
  113. buf[text_end-text] = '\0';
  114. glfwSetClipboardString(window, buf);
  115. free(buf);
  116. }
  117. // Shader sources
  118. // FIXME-OPT: clip at vertex level
  119. const GLchar* vertexSource =
  120. "#version 150 core\n"
  121. "uniform mat4 MVP;"
  122. "in vec2 i_pos;"
  123. "in vec2 i_uv;"
  124. "in vec4 i_col;"
  125. "out vec4 col;"
  126. "out vec2 pixel_pos;"
  127. "out vec2 uv;"
  128. "void main() {"
  129. " col = i_col;"
  130. " pixel_pos = i_pos;"
  131. " uv = i_uv;"
  132. " gl_Position = MVP * vec4(i_pos.x, i_pos.y, 0.0f, 1.0f);"
  133. "}";
  134. const GLchar* fragmentSource =
  135. "#version 150 core\n"
  136. "uniform sampler2D Tex;"
  137. "uniform vec4 ClipRect;"
  138. "in vec4 col;"
  139. "in vec2 pixel_pos;"
  140. "in vec2 uv;"
  141. "out vec4 o_col;"
  142. "void main() {"
  143. " o_col = texture(Tex, uv) * col;"
  144. //" if (pixel_pos.x < ClipRect.x || pixel_pos.y < ClipRect.y || pixel_pos.x > ClipRect.z || pixel_pos.y > ClipRect.w) discard;" // Clipping: using discard
  145. //" if (step(ClipRect.x,pixel_pos.x) * step(ClipRect.y,pixel_pos.y) * step(pixel_pos.x,ClipRect.z) * step(pixel_pos.y,ClipRect.w) < 1.0f) discard;" // Clipping: using discard and step
  146. " o_col.w *= (step(ClipRect.x,pixel_pos.x) * step(ClipRect.y,pixel_pos.y) * step(pixel_pos.x,ClipRect.z) * step(pixel_pos.y,ClipRect.w));" // Clipping: branch-less, set alpha 0.0f
  147. "}";
  148. static void glfw_error_callback(int error, const char* description)
  149. {
  150. fputs(description, stderr);
  151. }
  152. static float mouse_wheel = 0.0f;
  153. static void glfw_scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
  154. {
  155. mouse_wheel = (float)yoffset;
  156. }
  157. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
  158. {
  159. ImGuiIO& io = ImGui::GetIO();
  160. if (action == GLFW_PRESS)
  161. io.KeysDown[key] = true;
  162. if (action == GLFW_RELEASE)
  163. io.KeysDown[key] = false;
  164. io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
  165. io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
  166. }
  167. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  168. {
  169. if (c > 0 && c <= 255)
  170. ImGui::GetIO().AddInputCharacter((char)c);
  171. }
  172. // OpenGL code based on http://open.gl tutorials
  173. void InitGL()
  174. {
  175. glfwSetErrorCallback(glfw_error_callback);
  176. if (!glfwInit())
  177. exit(1);
  178. //glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  179. //glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
  180. //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  181. //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  182. glfwWindowHint(GLFW_REFRESH_RATE, 60);
  183. glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
  184. window = glfwCreateWindow(1280, 720, "ImGui OpenGL example", nullptr, nullptr);
  185. glfwMakeContextCurrent(window);
  186. glfwSetKeyCallback(window, glfw_key_callback);
  187. glfwSetScrollCallback(window, glfw_scroll_callback);
  188. glfwSetCharCallback(window, glfw_char_callback);
  189. glewExperimental = GL_TRUE;
  190. glewInit();
  191. GLenum err = GL_NO_ERROR;
  192. GLint status = GL_TRUE;
  193. err = glGetError(); IM_ASSERT(err == GL_NO_ERROR);
  194. // Create and compile the vertex shader
  195. vertexShader = glCreateShader(GL_VERTEX_SHADER);
  196. glShaderSource(vertexShader, 1, &vertexSource, NULL);
  197. glCompileShader(vertexShader);
  198. glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
  199. if (status != GL_TRUE)
  200. {
  201. char buffer[512];
  202. glGetShaderInfoLog(vertexShader, 1024, NULL, buffer);
  203. printf("%s", buffer);
  204. IM_ASSERT(status == GL_TRUE);
  205. }
  206. // Create and compile the fragment shader
  207. fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
  208. glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
  209. glCompileShader(fragmentShader);
  210. glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
  211. IM_ASSERT(status == GL_TRUE);
  212. // Link the vertex and fragment shader into a shader program
  213. shaderProgram = glCreateProgram();
  214. glAttachShader(shaderProgram, vertexShader);
  215. glAttachShader(shaderProgram, fragmentShader);
  216. glBindFragDataLocation(shaderProgram, 0, "o_col");
  217. glLinkProgram(shaderProgram);
  218. glGetProgramiv(shaderProgram, GL_LINK_STATUS, &status);
  219. IM_ASSERT(status == GL_TRUE);
  220. uniMVP = glGetUniformLocation(shaderProgram, "MVP");
  221. uniClipRect = glGetUniformLocation(shaderProgram, "ClipRect");
  222. // Create Vertex Buffer Objects & Vertex Array Objects
  223. glGenBuffers(1, &vbo);
  224. glBindBuffer(GL_ARRAY_BUFFER, vbo);
  225. glGenVertexArrays(1, &vao);
  226. glBindVertexArray(vao);
  227. GLint posAttrib = glGetAttribLocation(shaderProgram, "i_pos");
  228. glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), 0);
  229. glEnableVertexAttribArray(posAttrib);
  230. GLint uvAttrib = glGetAttribLocation(shaderProgram, "i_uv");
  231. glEnableVertexAttribArray(uvAttrib);
  232. glVertexAttribPointer(uvAttrib, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (void*)(2*sizeof(float)));
  233. GLint colAttrib = glGetAttribLocation(shaderProgram, "i_col");
  234. glVertexAttribPointer(colAttrib, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (void*)(4*sizeof(float)));
  235. glEnableVertexAttribArray(colAttrib);
  236. err = glGetError(); IM_ASSERT(err == GL_NO_ERROR);
  237. }
  238. void InitImGui()
  239. {
  240. int w, h;
  241. glfwGetWindowSize(window, &w, &h);
  242. ImGuiIO& io = ImGui::GetIO();
  243. io.DisplaySize = ImVec2((float)w, (float)h);
  244. io.DeltaTime = 1.0f/60.0f;
  245. io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB;
  246. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;
  247. io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;
  248. io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;
  249. io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;
  250. io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
  251. io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
  252. io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
  253. io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
  254. io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
  255. io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;
  256. io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;
  257. io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;
  258. io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;
  259. io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;
  260. io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
  261. io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
  262. io.RenderDrawListsFn = ImImpl_RenderDrawLists;
  263. io.SetClipboardTextFn = ImImpl_SetClipboardTextFn;
  264. io.GetClipboardTextFn = ImImpl_GetClipboardTextFn;
  265. // Load font texture
  266. glGenTextures(1, &fontTex);
  267. glBindTexture(GL_TEXTURE_2D, fontTex);
  268. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  269. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  270. const void* png_data;
  271. unsigned int png_size;
  272. ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size);
  273. int tex_x, tex_y, tex_comp;
  274. void* tex_data = stbi_load_from_memory((const unsigned char*)png_data, (int)png_size, &tex_x, &tex_y, &tex_comp, 0);
  275. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_x, tex_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_data);
  276. stbi_image_free(tex_data);
  277. }
  278. void Shutdown()
  279. {
  280. ImGui::Shutdown();
  281. glDeleteProgram(shaderProgram);
  282. glDeleteShader(fragmentShader);
  283. glDeleteShader(vertexShader);
  284. glDeleteBuffers(1, &vbo);
  285. glDeleteVertexArrays(1, &vao);
  286. glfwTerminate();
  287. }
  288. int main(int argc, char** argv)
  289. {
  290. InitGL();
  291. InitImGui();
  292. double time = glfwGetTime();
  293. while (!glfwWindowShouldClose(window))
  294. {
  295. ImGuiIO& io = ImGui::GetIO();
  296. glfwPollEvents();
  297. // 1) ImGui start frame, setup time delta & inputs
  298. const double current_time = glfwGetTime();
  299. io.DeltaTime = (float)(current_time - time);
  300. time = current_time;
  301. double mouse_x, mouse_y;
  302. glfwGetCursorPos(window, &mouse_x, &mouse_y);
  303. io.MousePos = ImVec2((float)mouse_x, (float)mouse_y);
  304. io.MouseDown[0] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) != 0;
  305. io.MouseDown[1] = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) != 0;
  306. io.MouseWheel = (mouse_wheel != 0) ? mouse_wheel > 0.0f ? 1 : - 1 : 0;
  307. mouse_wheel = 0.0f;
  308. ImGui::NewFrame();
  309. // 2) ImGui usage
  310. static bool show_test_window = true;
  311. static bool show_another_window = false;
  312. static float f;
  313. ImGui::Text("Hello, world!");
  314. ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
  315. show_test_window ^= ImGui::Button("Test Window");
  316. show_another_window ^= ImGui::Button("Another Window");
  317. // Calculate and show framerate
  318. static float ms_per_frame[120] = { 0 };
  319. static int ms_per_frame_idx = 0;
  320. static float ms_per_frame_accum = 0.0f;
  321. ms_per_frame_accum -= ms_per_frame[ms_per_frame_idx];
  322. ms_per_frame[ms_per_frame_idx] = io.DeltaTime * 1000.0f;
  323. ms_per_frame_accum += ms_per_frame[ms_per_frame_idx];
  324. ms_per_frame_idx = (ms_per_frame_idx + 1) % 120;
  325. const float ms_per_frame_avg = ms_per_frame_accum / 120;
  326. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", ms_per_frame_avg, 1000.0f / ms_per_frame_avg);
  327. if (show_test_window)
  328. {
  329. // More example code in ShowTestWindow()
  330. 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!
  331. ImGui::ShowTestWindow(&show_test_window);
  332. }
  333. if (show_another_window)
  334. {
  335. ImGui::Begin("Another Window", &show_another_window, ImVec2(200,100));
  336. ImGui::Text("Hello");
  337. ImGui::End();
  338. }
  339. // 3) Render
  340. glClearColor(0.8f, 0.6f, 0.6f, 1.0f);
  341. glClear(GL_COLOR_BUFFER_BIT);
  342. ImGui::Render();
  343. glfwSwapBuffers(window);
  344. }
  345. Shutdown();
  346. return 0;
  347. }