GCC Code Coverage Report


./
Coverage:
low: ≥ 0%
medium: ≥ 75.0%
high: ≥ 90.0%
Lines:
0 of 282, 0 excluded
0.0%
Functions:
0 of 29, 0 excluded
0.0%
Branches:
0 of 298, 0 excluded
0.0%

libs/imgui/src/eu/imgui/ui.cc
Line Branch Exec Source
1 #include "eu/imgui/ui.h"
2
3 // #include "klotter/cint.h"
4
5 #include "eu/core/ui.h"
6 #include "eu/render/texture.h"
7 #include "eu/render/dependency_glad.h"
8
9 #include <iostream>
10 #include <numbers>
11
12 #include "dear_imgui/imgui.h"
13 #include "dear_imgui/imgui_internal.h"
14
15 namespace eu::imgui
16 {
17
18 // opengl code copied from the imgui opengl3 backend with minor modifications
19 // todo(Gustav): should we use the imgui backend code for "backend" rendering or use our own shader?
20
21 static bool check_imgui_shader(GLuint handle, const char* desc)
22 {
23 GLint status = 0;
24 GLint log_length = 0;
25
26 glGetShaderiv(handle, GL_COMPILE_STATUS, &status);
27 glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length);
28 if (status == GL_FALSE)
29 {
30 std::cerr << "ERROR: Shader code: failed to compile " << desc << "!\n";
31 }
32
33 if (log_length > 1)
34 {
35 std::vector<GLchar> buf;
36 buf.resize(sizet_from_int(log_length + 1));
37 glGetShaderInfoLog(handle, log_length, nullptr, buf.data());
38 std::cerr << buf.data();
39 }
40 return status == GL_TRUE;
41 }
42
43 static bool imgui_check_program(GLuint handle, const char* desc)
44 {
45 GLint status = 0;
46 GLint log_length = 0;
47 glGetProgramiv(handle, GL_LINK_STATUS, &status);
48 glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length);
49 if (status == GL_FALSE)
50 {
51 std::cerr << "ERROR: Shader program: failed to link " << desc << "!\n";
52 }
53
54 if (log_length > 1)
55 {
56 std::vector<GLchar> buf;
57 buf.resize(sizet_from_int(log_length + 1));
58 glGetProgramInfoLog(handle, log_length, nullptr, buf.data());
59 std::cerr << buf.data();
60 }
61 return status == GL_TRUE;
62 }
63
64 void imgui_destroy_shader(ImguiShaderProgram* bd)
65 {
66 if (bd->program_handle == 0)
67 {
68 return;
69 }
70
71 glDeleteProgram(bd->program_handle);
72 bd->program_handle = 0;
73 }
74
75 ImguiShaderProgram imgui_load_shader(const char* glsl_version_string, const char* vertex_shader, const char* fragment_shader)
76 {
77 // Create shaders
78 const GLchar* vertex_shader_with_version[2] = {glsl_version_string, vertex_shader};
79 const auto vert_handle = glCreateShader(GL_VERTEX_SHADER);
80 glShaderSource(vert_handle, 2, vertex_shader_with_version, nullptr);
81 glCompileShader(vert_handle);
82 if (! check_imgui_shader(vert_handle, "vertex shader"))
83 {
84 return {};
85 }
86
87 const GLchar* fragment_shader_with_version[2] = {glsl_version_string, fragment_shader};
88 const auto frag_handle = glCreateShader(GL_FRAGMENT_SHADER);
89 glShaderSource(frag_handle, 2, fragment_shader_with_version, nullptr);
90 glCompileShader(frag_handle);
91
92 if (! check_imgui_shader(frag_handle, "fragment shader"))
93 {
94 return {};
95 }
96
97 // Link
98 ImguiShaderProgram prog;
99 prog.program_handle = glCreateProgram();
100 glAttachShader(prog.program_handle, vert_handle);
101 glAttachShader(prog.program_handle, frag_handle);
102 glLinkProgram(prog.program_handle);
103 if (! imgui_check_program(prog.program_handle, "shader program"))
104 {
105 imgui_destroy_shader(&prog);
106 return {};
107 }
108
109 glDetachShader(prog.program_handle, vert_handle);
110 glDetachShader(prog.program_handle, frag_handle);
111 glDeleteShader(vert_handle);
112 glDeleteShader(frag_handle);
113
114 prog.texture_attrib = glGetUniformLocation(prog.program_handle, "Texture");
115 prog.projection_attrib = glGetUniformLocation(prog.program_handle, "ProjMtx");
116 return prog;
117 }
118
119 constexpr auto dear_imgui_shader_version = "#version 330 core\n";
120
121 constexpr auto linear_to_gamma_glsl_vert = R"glsl(
122 layout (location = 0) in vec2 Position;
123 layout (location = 1) in vec2 UV;
124 layout (location = 2) in vec4 Color;
125 uniform mat4 ProjMtx;
126 out vec2 Frag_UV;
127 out vec4 Frag_Color;
128 void main()
129 {
130 Frag_UV = UV;
131 Frag_Color = Color;
132 gl_Position = ProjMtx * vec4(Position.xy,0,1);
133 }
134 )glsl";
135
136 constexpr auto linear_to_gamma_glsl_frag = R"glsl(
137 in vec2 Frag_UV;
138 in vec4 Frag_Color;
139 uniform sampler2D Texture;
140 layout (location = 0) out vec4 Out_Color;
141 void main()
142 {
143 vec4 sample = texture(Texture, Frag_UV.st);
144 vec3 color = sample.rgb / (sample.rgb + vec3(1.0f)); // reinhard tone mapping
145 float gamma = 2.2f;
146 vec3 gamma_corrected = pow(color.rgb, vec3(1.0f/gamma));
147 Out_Color = Frag_Color * vec4(gamma_corrected, sample.a);
148 }
149 )glsl";
150
151
152 constexpr auto depth_ortho_glsl_vert = R"glsl(
153 layout (location = 0) in vec2 Position;
154 layout (location = 1) in vec2 UV;
155 layout (location = 2) in vec4 Color;
156 uniform mat4 ProjMtx;
157 out vec2 Frag_UV;
158 out vec4 Frag_Color;
159 void main()
160 {
161 Frag_UV = UV;
162 Frag_Color = Color;
163 gl_Position = ProjMtx * vec4(Position.xy,0,1);
164 }
165 )glsl";
166
167 constexpr auto depth_ortho_glsl_frag = R"glsl(
168 in vec2 Frag_UV;
169 in vec4 Frag_Color;
170 uniform sampler2D Texture;
171 layout (location = 0) out vec4 Out_Color;
172
173 void main()
174 {
175 vec4 sample = texture(Texture, Frag_UV.st);
176 Out_Color = Frag_Color * vec4(vec3(sample.r), 1);
177 }
178 )glsl";
179
180
181 ImguiShaderCache::ImguiShaderCache()
182 : linear_to_gamma_shader(imgui_load_shader(dear_imgui_shader_version,
183 linear_to_gamma_glsl_vert, linear_to_gamma_glsl_frag))
184 , depth_ortho_shader(imgui_load_shader(dear_imgui_shader_version,
185 depth_ortho_glsl_vert, depth_ortho_glsl_frag)
186 )
187 {
188 }
189
190 ImguiShaderCache::~ImguiShaderCache()
191 {
192 imgui_destroy_shader(&linear_to_gamma_shader);
193 imgui_destroy_shader(&depth_ortho_shader);
194 }
195
196
197 void imgui_set_shared_shader_params(ImguiShaderProgram* prog)
198 {
199 ImDrawData* draw_data = ImGui::GetDrawData();
200
201 const auto le = draw_data->DisplayPos.x;
202 const auto ri = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
203 const auto to = draw_data->DisplayPos.y;
204 const auto bo = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
205
206 const float ortho_projection[4][4] = {
207 {2.0f / (ri - le), 0.0f, 0.0f, 0.0f},
208 {0.0f, 2.0f / (to - bo), 0.0f, 0.0f},
209 {0.0f, 0.0f, -1.0f, 0.0f},
210 {(ri + le) / (le - ri), (to + bo) / (bo - to), 0.0f, 1.0f},
211 };
212 glUseProgram(prog->program_handle);
213 glUniform1i(prog->texture_attrib, 0);
214 glUniformMatrix4fv(prog->projection_attrib, 1, GL_FALSE, &ortho_projection[0][0]);
215 }
216
217 void im_draw_callback_linear_to_gamma(const ImDrawList*, const ImDrawCmd* cmd)
218 {
219 auto* prog = static_cast<ImguiShaderProgram*>(cmd->UserCallbackData);
220
221 imgui_set_shared_shader_params(prog);
222 }
223
224 void im_draw_callback_depth_ortho(const ImDrawList*, const ImDrawCmd* cmd)
225 {
226 auto* prog = static_cast<ImguiShaderProgram*>(cmd->UserCallbackData);
227
228 imgui_set_shared_shader_params(prog);
229 }
230
231
232
233 void imgui_text(const std::string& str)
234 {
235 ImGui::Text("%s", str.c_str());
236 }
237
238
239
240 static void draw_imgui_image(const render::FrameBuffer& img, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& border_col, ImguiShaderCache* cache, ImageShader shader)
241 {
242 ImDrawList* draw_list = ImGui::GetWindowDrawList();
243
244 // set shader
245 switch (shader)
246 {
247 case ImageShader::TonemapAndGamma:
248 draw_list->AddCallback(im_draw_callback_linear_to_gamma, &cache->linear_to_gamma_shader);
249 break;
250 case ImageShader::DepthOrtho:
251 draw_list->AddCallback(im_draw_callback_depth_ortho, &cache->depth_ortho_shader);
252 break;
253 case ImageShader::None:
254 // no shader
255 break;
256 }
257
258 // draw image
259 ImGui::ImageWithBg(img.id, image_size, uv0, uv1, border_col);
260
261 // reset shader
262 if (shader != ImageShader::None)
263 {
264 draw_list->AddCallback(ImDrawCallback_ResetRenderState, nullptr);
265 }
266 }
267
268
269 static v2 v2_from_vec(const ImVec2& v)
270 {
271 return {v.x, v.y};
272 }
273
274
275 static void image_tooltip(const render::FrameBuffer& texture_id, const ImVec2 texture_size, const float& region_size, const float& hover_size,
276 const ImVec2 mouse_pos, const ImVec2 widget_size, const ImVec2 pos, const ImVec4 border_col, ImguiShaderCache* cache, ImageShader shader)
277 {
278 const auto region = core::calculate_region(v2_from_vec(mouse_pos), v2_from_vec(pos), v2_from_vec(texture_size), v2_from_vec(widget_size), region_size);
279 const auto flipped_region_y = texture_size.y - region.y;
280 const auto uv0 = ImVec2{region.x / texture_size.x, (flipped_region_y) / texture_size.y};
281 const auto uv1 = ImVec2{(region.x + region_size) / texture_size.x, (flipped_region_y - region_size) / texture_size.y};
282
283 // todo(Gustav): can we display pixel value instead of where we are looking? is the region important information?
284 imgui_text(fmt::format("UL: {} {}", region.x, region.y));
285 imgui_text(fmt::format("LR: {} {}", region.x + region_size, region.y + region_size));
286 draw_imgui_image(texture_id, ImVec2(hover_size, hover_size), uv0, uv1, border_col, cache, shader);
287 }
288
289
290
291 void imgui_image(const char* name, const render::FrameBuffer& img, ImguiShaderCache* cache, ImageShader shader)
292 {
293 const auto texture_size = ImVec2{float_from_int(img.size.width), float_from_int(img.size.height)};
294
295 // todo(Gustav): make the arguments widget_size and zoom level AND make them configurable (with scrolling)
296 static float widget_height = 100.0f;
297 static float region_size = 32.0f;
298 static float hover_size = 128.0f;
299 const auto& io = ImGui::GetIO();
300
301 imgui_text(fmt::format("{}: {}x{}", name, texture_size.x, texture_size.y));
302
303 const auto widget_width = (texture_size.x / texture_size.y) * widget_height;
304 const auto widget_size = ImVec2{widget_width, widget_height};
305
306 const auto pos = ImGui::GetCursorScreenPos();
307 constexpr auto uv_min = ImVec2{0.0f, 1.0f}; // Top-left
308 constexpr auto uv_max = ImVec2{1.0f, 0.0f}; // Lower-right
309 const auto border_col = ImGui::GetStyleColorVec4(ImGuiCol_Border);
310
311 static ImVec2 latest_tooltip;
312 static ImGuiID current_id = 0;
313
314 const constexpr char* const popup_id = "image config popup";
315
316 draw_imgui_image(img, widget_size, uv_min, uv_max, border_col, cache, shader);
317 const auto id = ImGui::GetID(name);
318
319 if (id == current_id && ImGui::BeginPopupContextItem(popup_id))
320 {
321 ImGui::DragFloat("Base", &widget_height, 1.0f);
322 ImGui::DragFloat("Size", &region_size, 0.01f);
323 ImGui::DragFloat("Scale", &hover_size, 1.0f);
324 image_tooltip(img, texture_size, region_size, hover_size, latest_tooltip, widget_size, pos, border_col, cache, shader);
325 if (ImGui::Button("Close"))
326 {
327 ImGui::CloseCurrentPopup();
328 }
329 ImGui::EndPopup();
330 }
331 ImGui::OpenPopupOnItemClick(popup_id, ImGuiPopupFlags_MouseButtonRight);
332
333 // todo(Gustav): look into SetItemTooltip and BeginItemTooltip from https://github.com/ocornut/imgui/releases/tag/v1.89.7
334 if (ImGui::IsItemHovered())
335 {
336 current_id = id;
337 latest_tooltip = io.MousePos;
338 if (ImGui::BeginTooltip())
339 {
340 image_tooltip(img, texture_size, region_size, hover_size, io.MousePos, widget_size, pos, border_col, cache, shader);
341 ImGui::EndTooltip();
342 }
343 }
344 }
345
346
347
348 bool simple_gamma_slider(const char* label, float* gamma, float curve, float min_gamma, float max_gamma)
349 {
350 if (curve < 0.0f)
351 {
352 return ImGui::SliderFloat(label, gamma, min_gamma, max_gamma);
353 }
354
355 // todo(Gustav): is this the correct way? it doesn't feel exactly right but perhaps that's just dear imgui
356 const auto gamma_range = max_gamma - min_gamma;
357 const auto t = (*gamma - min_gamma) / (gamma_range);
358
359 auto slider_value = std::pow(t, 1.0f / curve);
360 if (ImGui::SliderFloat(label, &slider_value, 0.0f, 1.0f) == false)
361 {
362 return false;
363 }
364
365 const auto perceptual = std::pow(slider_value, curve);
366 *gamma = min_gamma + perceptual * gamma_range;
367 return true;
368 }
369
370
371 bool drag(const char* const label, v3* drag)
372 {
373 return ImGui::DragFloat3(label, drag->get_data_ptr());
374 }
375
376 bool drag(const char* const label, Ypr* drag)
377 {
378 float angles[3] = {
379 drag->yaw.as_degrees(),
380 drag->pitch.as_degrees(),
381 drag->roll.as_degrees()
382 };
383
384 const auto changed = ImGui::DragFloat3(label, angles, 1.0f, -360.0f, 360.0f);
385
386 if (changed)
387 {
388 drag->yaw = An::from_degrees(angles[0]);
389 drag->pitch = An::from_degrees(angles[1]);
390 drag->roll = An::from_degrees(angles[2]);
391 }
392
393 return changed;
394 }
395
396 float length2(const ImVec2& v)
397 {
398 return v.x* v.x + v.y * v.y;
399 }
400
401 float length(const ImVec2& v)
402 {
403 return std::sqrt(v.x * v.x + v.y * v.y);
404 }
405
406 ImVec2 normalize(const ImVec2& v, float len)
407 {
408 return v / len;
409 }
410 ImVec2 normalize(const ImVec2& v)
411 {
412 return normalize(v, length(v));
413 }
414
415 float dot(const ImVec2& lhs, const ImVec2& rhs)
416 {
417 return lhs.x * rhs.x + lhs.y * rhs.y;
418 }
419 bool is_positive(float f)
420 {
421 return f >= 0.0f;
422 }
423
424 struct GearState
425 {
426 ImGuiID id;
427 ImVec2 center;
428 ImVec2 pos;
429 int turns;
430 float orig;
431 std::optional<float> initial_angle;
432 };
433
434 namespace
435 {
436 // dl functions are copied directly from ImDrawList with an additional starting angle and "special cases" removed.
437
438 void dl_PathArcToN(ImDrawList* dl, const ImVec2& center, float radius, float a_min, float a_max, int num_segments, float ang)
439 {
440 if (radius < 0.5f)
441 {
442 dl->_Path.push_back(center);
443 return;
444 }
445
446 // Note that we are adding a point at both a_min and a_max.
447 // If you are trying to draw a full closed circle you don't want the overlapping points!
448 dl->_Path.reserve(dl->_Path.Size + (num_segments + 1));
449 for (int i = 0; i <= num_segments; i++)
450 {
451 const float a = a_min + (static_cast<float>(i) / static_cast<float>(num_segments)) * (a_max - a_min);
452 dl->_Path.push_back(ImVec2(center.x + ImCos(a + ang) * radius, center.y + ImSin(a + ang) * radius));
453 }
454 }
455
456 void dl_PathArcTo(ImDrawList* dl, const ImVec2& center, float radius, float a_min, float a_max, int num_segments, float ang)
457 {
458 if (radius < 0.5f)
459 {
460 dl->_Path.push_back(center);
461 return;
462 }
463
464 dl_PathArcToN(dl, center, radius, a_min, a_max, num_segments, ang);
465 }
466
467 void dl_AddCircle(ImDrawList* dl, const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness, float ang)
468 {
469 if ((col & IM_COL32_A_MASK) == 0 || radius < 0.5f)
470 {
471 return;
472 }
473
474 // Explicit segment count (still clamp to avoid drawing insanely tessellated shapes)
475 num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX);
476
477 // Because we are filling a closed shape we remove 1 from the count of segments/points
478 const float a_max = (IM_PI * 2.0f) * (static_cast<float>(num_segments) - 1.0f) / static_cast<float>(num_segments);
479 dl_PathArcTo(dl, center, radius - 0.5f, 0.0f, a_max, num_segments - 1, ang);
480
481 dl->PathStroke(col, ImDrawFlags_Closed, thickness);
482 }
483 }
484
485 // https://anttweakbar.sourceforge.io/doc/tools_anttweakbar_rotoslider.html
486 bool gear_icon(const char* const label, float* drag)
487 {
488 static std::optional<GearState> state = std::nullopt;
489
490 // config
491 const auto circle_col = ImColor(100, 100, 255);
492 const float min_radius = 20.0f;
493 const float radius = min_radius;
494 const float one_turn = 10.0f;
495 constexpr float circle_thickness = 1.0f;
496 constexpr int gear_segments = 6;
497
498 const auto mp = ImGui::GetMousePos();
499
500 ImGui::Button(label);
501 const auto id = ImGui::GetItemID();
502 const auto active = ImGui::IsItemActive();
503
504 if (active && state && state->id != id)
505 {
506 // another id is active, but so are we => treat it as the previous lost the activity
507 state = std::nullopt;
508 }
509
510 auto orig = state ? state->orig : *drag;
511 const auto center = state.has_value() ? state->center : mp;
512
513 // interaction
514 bool changed = false;
515 if (state.has_value() == false || state->id == id)
516 {
517 // only change state if we are the interactive item or there is no interactive item
518 if (active)
519 {
520 int turns = state ? state->turns : 0;
521 const auto input = mp - center;
522 std::optional<float> initial_angle = state ? state->initial_angle : std::nullopt;
523 if (length2(input) > (min_radius * min_radius))
524 {
525 const auto dir_cur = normalize(input);
526 const auto ang_right = std::acos(dot(dir_cur, {1, 0})) * (180.0f/std::numbers::pi_v<float>);
527 const auto ang = dir_cur.y < 0 ? ang_right : 360 - ang_right;
528
529 if (initial_angle.has_value() == false)
530 {
531 initial_angle = ang;
532 }
533
534 if (state.has_value())
535 {
536 const auto changed_y = is_positive(input.y) != is_positive(state->pos.y);
537 const auto on_right_side = input.x > 0 && state->pos.x > 0;
538 const auto changed_dir = changed_y && on_right_side;
539 if (changed_dir)
540 {
541 turns += is_positive(input.y) ? -1 : 1;
542 }
543 }
544 const auto new_ang = ang - *initial_angle + static_cast<float>(turns) * 360.0f;
545 const auto val = orig + (new_ang / 360.0f) * one_turn;
546
547 if (drag)
548 {
549 *drag = val;
550 changed = true;
551 }
552 }
553 else
554 {
555 initial_angle = std::nullopt;
556 turns = 0;
557 orig = *drag;
558 }
559
560 state = GearState
561 {
562 .id = id,
563 .center = center,
564 .pos = input,
565 .turns = turns,
566 .orig = orig,
567 .initial_angle = initial_angle
568 };
569 }
570 else
571 {
572 state = std::nullopt;
573 }
574 }
575
576 // drawing
577 {
578 // draw gear
579 if (active)
580 {
581 auto* fg = ImGui::GetForegroundDrawList();
582 // fg->AddCircle(center, radius, circle_col, gear_segments, thickness);
583 const auto ang = (std::fmodf(*drag, one_turn)/one_turn) * -2.0f * IM_PI;
584 dl_AddCircle(fg, center, radius, circle_col, gear_segments, circle_thickness, ang);
585
586 // draw wrench instead?
587 fg->AddLine(center, mp, circle_col);
588 }
589 }
590
591 return changed;
592 }
593
594 bool gear(const char* const label, v3* drag)
595 {
596 auto& style = ImGui::GetStyle();
597
598 bool value_changed = false;
599 ImGui::BeginGroup();
600 ImGui::PushID(label);
601 ImGui::PushMultiItemsWidths(3, ImGui::CalcItemWidth());
602 const auto widget = [&](int i, float* p_data)
603 {
604 ImGui::PushID(i);
605 if (i > 0)
606 ImGui::SameLine(0, style.ItemInnerSpacing.x);
607 value_changed |= ImGui::DragFloat("", p_data);
608 ImGui::SameLine(0, style.ItemInnerSpacing.x);
609 value_changed |= gear_icon(".", p_data);
610 ImGui::PopID();
611 ImGui::PopItemWidth();
612 };
613 widget(0, &drag->x);
614 widget(1, &drag->y);
615 widget(2, &drag->z);
616 ImGui::PopID();
617
618 const char* label_end = ImGui::FindRenderedTextEnd(label);
619 if (label != label_end)
620 {
621 ImGui::SameLine(0, style.ItemInnerSpacing.x);
622 ImGui::TextEx(label, label_end);
623 }
624
625 ImGui::EndGroup();
626
627 return value_changed;
628 }
629
630 }
631
632