1 #include "ImGuiRenderer.h"
2 #include <QDateTime>
3 #include <QGuiApplication>
4 #include <QMouseEvent>
5 #include <QClipboard>
6 #include <QCursor>
7 #include <QDebug>
8
9 namespace QtImGui {
10
11 namespace {
12
13 QHash<int, ImGuiKey> keyMap = {
14 { Qt::Key_Tab, ImGuiKey_Tab },
15 { Qt::Key_Left, ImGuiKey_LeftArrow },
16 { Qt::Key_Right, ImGuiKey_RightArrow },
17 { Qt::Key_Up, ImGuiKey_UpArrow },
18 { Qt::Key_Down, ImGuiKey_DownArrow },
19 { Qt::Key_PageUp, ImGuiKey_PageUp },
20 { Qt::Key_PageDown, ImGuiKey_PageDown },
21 { Qt::Key_Home, ImGuiKey_Home },
22 { Qt::Key_End, ImGuiKey_End },
23 { Qt::Key_Delete, ImGuiKey_Delete },
24 { Qt::Key_Backspace, ImGuiKey_Backspace },
25 { Qt::Key_Enter, ImGuiKey_Enter },
26 { Qt::Key_Escape, ImGuiKey_Escape },
27 { Qt::Key_A, ImGuiKey_A },
28 { Qt::Key_C, ImGuiKey_C },
29 { Qt::Key_V, ImGuiKey_V },
30 { Qt::Key_X, ImGuiKey_X },
31 { Qt::Key_Y, ImGuiKey_Y },
32 { Qt::Key_Z, ImGuiKey_Z },
33 };
34
35 QByteArray g_currentClipboardText;
36
37 }
38
initialize(WindowWrapper * window)39 void ImGuiRenderer::initialize(WindowWrapper *window) {
40 m_window.reset(window);
41 initializeOpenGLFunctions();
42 g_fun = new QOpenGLFunctions_3_2_Core();
43 g_fun->initializeOpenGLFunctions();
44
45 ImGui::CreateContext();
46
47 ImGuiIO &io = ImGui::GetIO();
48 for (ImGuiKey key : keyMap.values()) {
49 io.KeyMap[key] = key;
50 }
51
52 io.RenderDrawListsFn = [](ImDrawData *drawData) {
53 instance()->renderDrawList(drawData);
54 };
55 io.SetClipboardTextFn = [](void *user_data, const char *text) {
56 Q_UNUSED(user_data);
57 QGuiApplication::clipboard()->setText(text);
58 };
59 io.GetClipboardTextFn = [](void *user_data) {
60 Q_UNUSED(user_data);
61 g_currentClipboardText = QGuiApplication::clipboard()->text().toUtf8();
62 return (const char *)g_currentClipboardText.data();
63 };
64 io.IniFilename = nullptr;
65
66 window->installEventFilter(this);
67 }
68
renderDrawList(ImDrawData * draw_data)69 void ImGuiRenderer::renderDrawList(ImDrawData *draw_data)
70 {
71 // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
72 ImGuiIO& io = ImGui::GetIO();
73 int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
74 int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
75 if (fb_width == 0 || fb_height == 0)
76 return;
77 draw_data->ScaleClipRects(io.DisplayFramebufferScale);
78
79 // Backup GL state
80 GLint last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, &last_active_texture);
81 glActiveTexture(GL_TEXTURE0);
82 GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
83 GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
84 GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
85 GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
86 GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
87 GLint last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, &last_blend_src_rgb);
88 GLint last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, &last_blend_dst_rgb);
89 GLint last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, &last_blend_src_alpha);
90 GLint last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, &last_blend_dst_alpha);
91 GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb);
92 GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
93 GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
94 GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
95 GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
96 GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
97 GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
98 GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
99
100 // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
101 glEnable(GL_BLEND);
102 glBlendEquation(GL_FUNC_ADD);
103 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
104 glDisable(GL_CULL_FACE);
105 glDisable(GL_DEPTH_TEST);
106 glEnable(GL_SCISSOR_TEST);
107
108 // Setup viewport, orthographic projection matrix
109 glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
110 const float ortho_projection[4][4] =
111 {
112 { 2.0f/io.DisplaySize.x, 0.0f, 0.0f, 0.0f },
113 { 0.0f, 2.0f/-io.DisplaySize.y, 0.0f, 0.0f },
114 { 0.0f, 0.0f, -1.0f, 0.0f },
115 {-1.0f, 1.0f, 0.0f, 1.0f },
116 };
117 glUseProgram(g_ShaderHandle);
118 glUniform1i(g_AttribLocationTex, 0);
119 glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
120 g_fun->glBindVertexArray(g_VaoHandle);
121
122 for (int n = 0; n < draw_data->CmdListsCount; n++)
123 {
124 const ImDrawList* cmd_list = draw_data->CmdLists[n];
125 const ImDrawIdx* idx_buffer_offset = 0;
126
127 glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
128 glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW);
129
130 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
131 glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW);
132
133 for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
134 {
135 const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
136 if (pcmd->UserCallback)
137 {
138 pcmd->UserCallback(cmd_list, pcmd);
139 }
140 else
141 {
142 glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
143 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));
144 glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
145 }
146 idx_buffer_offset += pcmd->ElemCount;
147 }
148 }
149
150 // Restore modified GL state
151 glUseProgram(last_program);
152 glBindTexture(GL_TEXTURE_2D, last_texture);
153 glActiveTexture(last_active_texture);
154 g_fun->glBindVertexArray(last_vertex_array);
155 glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
156 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
157 glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
158 glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha);
159 if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
160 if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
161 if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
162 if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
163 glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
164 glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
165 }
166
createFontsTexture()167 bool ImGuiRenderer::createFontsTexture()
168 {
169 // Build texture atlas
170 ImGuiIO& io = ImGui::GetIO();
171 unsigned char* pixels;
172 int width, height;
173 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.
174
175 // Upload texture to graphics system
176 GLint last_texture;
177 glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
178 glGenTextures(1, &g_FontTexture);
179 glBindTexture(GL_TEXTURE_2D, g_FontTexture);
180 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
181 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
182 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
183
184 // Store our identifier
185 io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
186
187 // Restore state
188 glBindTexture(GL_TEXTURE_2D, last_texture);
189
190 return true;
191 }
192
createDeviceObjects()193 bool ImGuiRenderer::createDeviceObjects()
194 {
195 // Backup GL state
196 GLint last_texture, last_array_buffer, last_vertex_array;
197 glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
198 glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
199 glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
200
201 const GLchar *vertex_shader =
202 "#version 330\n"
203 "uniform mat4 ProjMtx;\n"
204 "in vec2 Position;\n"
205 "in vec2 UV;\n"
206 "in vec4 Color;\n"
207 "out vec2 Frag_UV;\n"
208 "out vec4 Frag_Color;\n"
209 "void main()\n"
210 "{\n"
211 " Frag_UV = UV;\n"
212 " Frag_Color = Color;\n"
213 " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
214 "}\n";
215
216 const GLchar* fragment_shader =
217 "#version 330\n"
218 "uniform sampler2D Texture;\n"
219 "in vec2 Frag_UV;\n"
220 "in vec4 Frag_Color;\n"
221 "out vec4 Out_Color;\n"
222 "void main()\n"
223 "{\n"
224 " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n"
225 "}\n";
226
227 g_ShaderHandle = glCreateProgram();
228 g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
229 g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
230 glShaderSource(g_VertHandle, 1, &vertex_shader, 0);
231 glShaderSource(g_FragHandle, 1, &fragment_shader, 0);
232 glCompileShader(g_VertHandle);
233 glCompileShader(g_FragHandle);
234 glAttachShader(g_ShaderHandle, g_VertHandle);
235 glAttachShader(g_ShaderHandle, g_FragHandle);
236 glLinkProgram(g_ShaderHandle);
237
238 g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
239 g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
240 g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position");
241 g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV");
242 g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color");
243
244 glGenBuffers(1, &g_VboHandle);
245 glGenBuffers(1, &g_ElementsHandle);
246
247 g_fun->glGenVertexArrays(1, &g_VaoHandle);
248 g_fun->glBindVertexArray(g_VaoHandle);
249 glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
250 glEnableVertexAttribArray(g_AttribLocationPosition);
251 glEnableVertexAttribArray(g_AttribLocationUV);
252 glEnableVertexAttribArray(g_AttribLocationColor);
253
254 #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
255 glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
256 glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
257 glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
258 #undef OFFSETOF
259
260 createFontsTexture();
261
262 // Restore modified GL state
263 glBindTexture(GL_TEXTURE_2D, last_texture);
264 glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
265 g_fun->glBindVertexArray(last_vertex_array);
266
267 return true;
268 }
269
newFrame()270 void ImGuiRenderer::newFrame()
271 {
272 if (!g_FontTexture)
273 createDeviceObjects();
274
275 ImGuiIO& io = ImGui::GetIO();
276
277 // Setup display size (every frame to accommodate for window resizing)
278 io.DisplaySize = ImVec2(m_window->size().width(), m_window->size().height());
279 io.DisplayFramebufferScale = ImVec2(m_window->devicePixelRatio(), m_window->devicePixelRatio());
280
281 // Setup time step
282 double current_time = QDateTime::currentMSecsSinceEpoch() / double(1000);
283 io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
284 g_Time = current_time;
285
286 // Setup inputs
287 // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
288 if (m_window->isActive())
289 {
290 auto pos = m_window->mapFromGlobal(QCursor::pos());
291 io.MousePos = ImVec2(pos.x(), pos.y()); // Mouse position in screen coordinates (set to -1,-1 if no mouse / on another screen, etc.)
292 }
293 else
294 {
295 io.MousePos = ImVec2(-1,-1);
296 }
297
298 for (int i = 0; i < 3; i++)
299 {
300 io.MouseDown[i] = g_MousePressed[i];
301 }
302
303 io.MouseWheelH = g_MouseWheelH;
304 io.MouseWheel = g_MouseWheel;
305 g_MouseWheelH = 0;
306 g_MouseWheel = 0;
307
308 // Hide OS mouse cursor if ImGui is drawing it
309 // glfwSetInputMode(g_Window, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL);
310
311 // Start the frame
312 ImGui::NewFrame();
313 }
314
onMousePressedChange(QMouseEvent * event)315 void ImGuiRenderer::onMousePressedChange(QMouseEvent *event)
316 {
317 g_MousePressed[0] = event->buttons() & Qt::LeftButton;
318 g_MousePressed[1] = event->buttons() & Qt::RightButton;
319 g_MousePressed[2] = event->buttons() & Qt::MiddleButton;
320 }
321
onWheel(QWheelEvent * event)322 void ImGuiRenderer::onWheel(QWheelEvent *event)
323 {
324 // 5 lines per unit
325 g_MouseWheelH += event->pixelDelta().x() / (ImGui::GetTextLineHeight());
326 g_MouseWheel += event->pixelDelta().y() / (5.0 * ImGui::GetTextLineHeight());
327 }
328
onKeyPressRelease(QKeyEvent * event)329 void ImGuiRenderer::onKeyPressRelease(QKeyEvent *event)
330 {
331 ImGuiIO& io = ImGui::GetIO();
332 if (keyMap.contains(event->key())) {
333 io.KeysDown[keyMap[event->key()]] = event->type() == QEvent::KeyPress;
334 }
335
336 if (event->type() == QEvent::KeyPress) {
337 QString text = event->text();
338 if (text.size() == 1) {
339 io.AddInputCharacter(text.at(0).unicode());
340 }
341 }
342
343 #ifdef Q_OS_MAC
344 io.KeyCtrl = event->modifiers() & Qt::MetaModifier;
345 io.KeyShift = event->modifiers() & Qt::ShiftModifier;
346 io.KeyAlt = event->modifiers() & Qt::AltModifier;
347 io.KeySuper = event->modifiers() & Qt::ControlModifier; // Comamnd key
348 #else
349 io.KeyCtrl = event->modifiers() & Qt::ControlModifier;
350 io.KeyShift = event->modifiers() & Qt::ShiftModifier;
351 io.KeyAlt = event->modifiers() & Qt::AltModifier;
352 io.KeySuper = event->modifiers() & Qt::MetaModifier;
353 #endif
354 }
355
eventFilter(QObject * watched,QEvent * event)356 bool ImGuiRenderer::eventFilter(QObject *watched, QEvent *event)
357 {
358 switch (event->type()) {
359 case QEvent::MouseButtonPress:
360 case QEvent::MouseButtonRelease:
361 this->onMousePressedChange(static_cast<QMouseEvent *>(event));
362 break;
363 case QEvent::Wheel:
364 this->onWheel(static_cast<QWheelEvent *>(event));
365 break;
366 case QEvent::KeyPress:
367 case QEvent::KeyRelease:
368 this->onKeyPressRelease(static_cast<QKeyEvent *>(event));
369 break;
370 default:
371 break;
372 }
373 return QObject::eventFilter(watched, event);
374 }
375
instance()376 ImGuiRenderer* ImGuiRenderer::instance() {
377 static ImGuiRenderer* instance = nullptr;
378 if (!instance) {
379 instance = new ImGuiRenderer();
380 }
381 return instance;
382 }
383
384 }
385