Easy3D 3.0.0
Loading...
Searching...
No Matches
Tutorial_202_Viewer_imgui

Adding a custom menu bar and widgets to the Easy3D Viewer with Dear ImGui.

Overview

The default Viewer already offers a rich interaction model, but applications often need their own menus, buttons, and dialogs. This tutorial shows how to layer a Dear ImGui GUI on top of the Viewer by subclassing it (ViewerImGui, shown after this file). The entry point is identical to Tutorial_201 except that it instantiates ViewerImGui instead of Viewer; all of the GUI logic lives in the subclass.

The technique

Dear ImGui is an immediate-mode GUI: rather than building a persistent widget tree, you describe the UI every frame by calling functions like BeginMainMenuBar(), MenuItem(), and Text(). Each call both renders the widget and reports whether the user interacted with it, so the same code that draws a "File > Open" item also triggers the open() action when it is clicked. The ViewerImGui subclass hooks into the viewer's frame at three points: init() creates the ImGui context and GLFW backend, pre_draw() starts an ImGui frame, lets draw_gui() emit the widgets, then converts ImGui's draw lists into Easy3D overlay draw commands, and post_resize() keeps ImGui's display size in sync with the window. Mouse/keyboard events are routed through callbacks so that clicks on the GUI are consumed by ImGui instead of rotating the scene. See the ViewerImGui class for the full integration.

Easy3D API

Running it

A window opens with a menu bar at the top. Use File to open/save models or quit, View to take a snapshot, and Help to show an About dialog. The 3D scene underneath remains fully navigable; clicks on the menus are handled by ImGui rather than the camera.

1
27#include <easy3d/renderer/camera.h>
28#include <easy3d/util/resource.h>
29#include <easy3d/util/initializer.h>
30
31#include "viewer.h"
32
81using namespace easy3d;
82
83int main(int argc, char **argv) {
84 // Bootstrap Easy3D (logging, resource directory, ...). Must come first.
85 initialize();
86
87 // A bundled sample model shipped with Easy3D's resource data.
88 const std::string file_name = resource::directory() + "/data/easy3d.ply";
89
90 // Create the ImGui-enhanced viewer instead of the plain Viewer.
91 ViewerImGui viewer(EXAMPLE_TITLE);
92
93 // Orient the camera to a standard front view: look along -Z with +Y pointing up.
94 viewer.camera()->set_view_direction(vec3(0, 0, -1));
95 viewer.camera()->set_up_vector(vec3(0, 1, 0));
96
97 // Load the model into the viewer (which takes ownership); report failure if any.
98 if (!viewer.add_model(file_name)) {
99 std::cerr << "failed to load model. Please make sure the file exists and format is correct" << std::endl;
100 return EXIT_FAILURE;
101 }
102
103 // Enter the interactive render loop; returns only when the window is closed.
104 return viewer.run();
105}
Definition collider.cpp:182

The header file of the viewer class:

1
27#ifndef EASY3D_TUTORIAL_VIEWER_IMGUI_H
28#define EASY3D_TUTORIAL_VIEWER_IMGUI_H
29
30#include <easy3d/viewer/viewer.h>
31
32// A very good tutorial for imgui:
33// https://eliasdaler.github.io/using-imgui-with-sfml-pt1/
34// https://eliasdaler.github.io/using-imgui-with-sfml-pt2/
35
36struct ImGuiContext;
37
38
54class ViewerImGui : public easy3d::Viewer {
55public:
62 explicit ViewerImGui(
63 const std::string &title = "Easy3D ViewerImGui",
64 const easy3d::WindowOptions &window = {},
65 const easy3d::DeviceOptions &options = {}
66 );
67
71 ~ViewerImGui() override;
72
73protected:
74 // Creates the ImGui context, GLFW backend, and font atlas.
75 void init() override;
76
77 // Starts an ImGui frame, draws the widgets, and converts them to viewer overlays.
78 void pre_draw() override;
79
80 // Keeps ImGui's display size in sync when the window is resized.
81 void post_resize(int w, int h) override;
82
83 // Input hooks: return true while ImGui owns the mouse/keyboard, so the gesture
84 // does not also navigate the 3D scene.
85 bool mouse_press_event(int x, int y, int button, int modifiers) override;
86 bool mouse_release_event(int x, int y, int button, int modifiers) override;
87 bool mouse_drag_event(int x, int y, int dx, int dy, int button, int modifiers) override;
88 bool mouse_free_move_event(int x, int y, int dx, int dy, int modifiers) override;
89 bool mouse_scroll_event(int x, int y, int dx, int dy) override;
90 bool key_press_event(int key, int modifiers) override;
91 bool key_release_event(int key, int modifiers) override;
92 bool char_input_event(unsigned int codepoint) override;
93
94 // Override to add widgets, then call ViewerImGui::draw_gui() to finish the frame.
95 virtual void draw_gui();
96
97 // The individual top-level menus emitted by draw_gui().
98 // "File": open/save/quit items, dispatched to open()/save()/request_close().
99 void draw_menu_file();
100 // "View": the snapshot item, dispatched to snapshot().
101 void draw_menu_view();
102
103protected:
104 // Ratio between the framebuffer size and the window size.
105 // May be different from the DPI scaling!
106 float pixel_ratio();
107
108 // Scale factor applied to widgets so they stay crisp on high-DPI displays.
109 float widget_scaling() {
110 return dpi_scaling() / pixel_ratio();
111 }
112
113 // Rebuild the font atlas for this viewer.
114 void reload_font(int font_size = 16);
115
116protected:
117 // Each viewer owns its UI context.
118 ImGuiContext *context_ = nullptr;
119
120 float menu_height_ = 0;
121 std::shared_ptr<const easy3d::graphics::Image> font_image_;
122};
123
124
125#endif // EASY3D_TUTORIAL_VIEWER_IMGUI_H
The default viewer implementation for both OpenGL and Vulkan backends.
Definition viewer.h:143
Options for creating a host viewer on the configured backend.
Definition viewer.h:99
Window settings of a Viewer - the part both backends agree on.
Definition viewer.h:72

The source file of viewer class:

1
27#include "viewer.h"
28
29#include <easy3d/util/file_system.h>
30#include <easy3d/core/point_cloud.h>
31#include <easy3d/core/surface_mesh.h>
32#include <easy3d/renderer/camera.h>
33
34#define GLFW_INCLUDE_NONE
35#include <3rd_party/glfw/include/GLFW/glfw3.h> // for glfw functions
36
37#include <3rd_party/imgui/misc/fonts/imgui_fonts_droid_sans.h>
38#include <3rd_party/imgui/imgui.h>
39#include <3rd_party/imgui/backends/imgui_impl_glfw.h>
40#include <algorithm>
41#include <cmath>
42#include <stdexcept>
43
44using namespace easy3d;
45
46// \cond
47
48// Forward all window/backend settings to the base Viewer; the GUI itself is set up later
49// in init(), once the window and rendering context exist.
50ViewerImGui::ViewerImGui(const std::string &title,
51 const WindowOptions &window,
52 const DeviceOptions &options
53 ) : Viewer(title, window, options)
54{
55 // Liangliang: the internal glfw won't be shared across dll boundaries (Linux and macOS resolve GLFW to one instance).
56 // See https://github.com/LiangliangNan/Easy3D/issues/178
57 // Details: The vendored GLFW is a private dependency of easy3d_viewer, so an inherited viewer that calls GLFW
58 // itself links its own copy of the static library. On Windows that copy was never initialized and every
59 // public GLFW function returns without touching the window (_GLFW_REQUIRE_INIT_OR_RETURN), so
60 // glfwSetKeyCallback(window, nullptr) hands back a null host callback and the synthetic input driven
61 // from it faults. Initializing the local copy makes these calls work on the window the library created; the
62 // two modules register separate window classes, so this is safe. .
63#if defined(_WIN32) && defined(_MSC_VER)
64 if (!glfwInit())
65 throw std::runtime_error("glfwInit failed for ViewerImGui's GLFW copy");
66#endif
67}
68
69ViewerImGui::~ViewerImGui() {
70 if (!context_)
71 return;
72 // Tear down ImGui in reverse order of setup: shut down the GLFW backend, then
73 // destroy the context. The base Viewer handles the rest.
74 ImGui::SetCurrentContext(context_);
75 if (ImGui::GetIO().BackendPlatformUserData)
76 ImGui_ImplGlfw_Shutdown();
77 ImGui::DestroyContext(context_);
78 context_ = nullptr; // input hooks may still run while the window is being torn down
79
80 // Not needed: it will be called in the destructor of the base class
81 //Viewer::cleanup();
82}
83
84// One-time GUI setup, called by the viewer after the window/context are ready.
85void ViewerImGui::init() {
86 Viewer::init();
87
88 if (!context_) {
89 // Setup ImGui binding
90 IMGUI_CHECKVERSION();
91
92 // Each viewer owns a separate ImGui context (ImGui is otherwise global-state based).
93 context_ = ImGui::CreateContext();
94
95 // Bind ImGui to GLFW for input/time; "InitForOther" leaves rendering to Easy3D.
96 if (!ImGui_ImplGlfw_InitForOther(window(), true))
97 throw std::runtime_error("could not initialize ImGui GLFW backend");
98 ImGui::GetIO().BackendRendererName = "Easy3D annotations";
99 ImGui::GetIO().BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset;
100 ImGuiIO &io = ImGui::GetIO();
101 io.WantCaptureKeyboard = true;
102 io.WantTextInput = true;
103 io.IniFilename = nullptr; // do not persist window layout to an .ini file
104 ImGui::StyleColorsLight();
105 ImGuiStyle &style = ImGui::GetStyle();
106 style.FrameRounding = 5.0f;
107
108 // load font
109 reload_font();
110 }
111}
112
113// Routes input through ImGui first: while a menu, popup or text field owns the
114// mouse/keyboard, the hook returns true so the viewer skips its built-in controls.
115namespace {
116 // The viewer window exists before the lazy init() creates the ImGui context, so window
117 // events can reach the hooks with no context (or after teardown destroyed it).
118 bool imgui_wants_mouse(ImGuiContext *context) {
119 if (!context)
120 return false;
121 ImGui::SetCurrentContext(context);
122 return ImGui::GetIO().WantCaptureMouse;
123 }
124
125 bool imgui_wants_keyboard(ImGuiContext *context) {
126 if (!context)
127 return false;
128 ImGui::SetCurrentContext(context);
129 return ImGui::GetIO().WantCaptureKeyboard ||
130 ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopup);
131 }
132} // namespace
133
134bool ViewerImGui::mouse_press_event(int x, int y, int button, int modifiers) {
135 return imgui_wants_mouse(context_) || Viewer::mouse_press_event(x, y, button, modifiers);
136}
137
138bool ViewerImGui::mouse_release_event(int x, int y, int button, int modifiers) {
139 return imgui_wants_mouse(context_) || Viewer::mouse_release_event(x, y, button, modifiers);
140}
141
142bool ViewerImGui::mouse_drag_event(int x, int y, int dx, int dy, int button, int modifiers) {
143 return imgui_wants_mouse(context_) || Viewer::mouse_drag_event(x, y, dx, dy, button, modifiers);
144}
145
146bool ViewerImGui::mouse_free_move_event(int x, int y, int dx, int dy, int modifiers) {
147 return imgui_wants_mouse(context_) || Viewer::mouse_free_move_event(x, y, dx, dy, modifiers);
148}
149
150bool ViewerImGui::mouse_scroll_event(int x, int y, int dx, int dy) {
151 return imgui_wants_mouse(context_) || Viewer::mouse_scroll_event(x, y, dx, dy);
152}
153
154bool ViewerImGui::key_press_event(int key, int modifiers) {
155 return imgui_wants_keyboard(context_) || Viewer::key_press_event(key, modifiers);
156}
157
158bool ViewerImGui::key_release_event(int key, int modifiers) {
159 return imgui_wants_keyboard(context_) || Viewer::key_release_event(key, modifiers);
160}
161
162bool ViewerImGui::char_input_event(unsigned int codepoint) {
163 return imgui_wants_keyboard(context_) || Viewer::char_input_event(codepoint);
164}
165
166// Framebuffer pixels per window pixel; >1 on high-DPI (e.g. Retina) displays.
167float ViewerImGui::pixel_ratio() {
168 // Computes pixel ratio for hidpi devices
169 int fw = framebuffer_width();
170 int vw = width();
171 return static_cast<float>(fw) / static_cast<float>(vw);
172}
173
174// Rebuilds the font atlas at the current DPI and provides it as an Easy3D image so the
175// overlay renderer can sample it. Called at init and whenever the pixel ratio changes.
176void ViewerImGui::reload_font(int font_size) {
177 ImGuiIO &io = ImGui::GetIO();
178 io.Fonts->Clear();
179 io.Fonts->AddFontFromMemoryCompressedTTF(droid_sans_compressed_data, droid_sans_compressed_size,
180 static_cast<float>(font_size) * dpi_scaling());
181 io.FontGlobalScale = 1.0f / pixel_ratio();
182 // Rasterize the glyphs into an RGBA bitmap...
183 unsigned char *pixels;
184 int w, h;
185 io.Fonts->GetTexDataAsRGBA32(&pixels, &w, &h);
186 graphics::Sampler sampler;
187 sampler.filter = graphics::TextureFilter::linear;
188 // ...wrap it in an Easy3D graphics::Image (the overlay texture)...
189 font_image_ = std::make_shared<graphics::Image>(
190 w, h, std::vector<unsigned char>(pixels, pixels + size_t(w) * h * 4), sampler);
191 // ...and tell ImGui to use that texture id when drawing text.
192 io.Fonts->SetTexID(ImTextureID(reinterpret_cast<uintptr_t>(font_image_.get())));
193}
194
195void ViewerImGui::post_resize(int w, int h) {
196 Viewer::post_resize(w, h);
197 if (context_) {
198 // ImGui lays out widgets against this display size, so keep it current.
199 ImGui::GetIO().DisplaySize.x = float(w);
200 ImGui::GetIO().DisplaySize.y = float(h);
201 }
202}
203
204// The heart of the integration: build the ImGui frame, then translate its draw lists into
205// Easy3D overlay draw commands that the viewer composites on top of the 3D scene.
206void ViewerImGui::pre_draw() {
207 ImGui::SetCurrentContext(context_);
208 ImGui_ImplGlfw_NewFrame();
209 // Re-bake the font if the DPI/pixel ratio changed since the last frame.
210 if (std::abs(ImGui::GetIO().FontGlobalScale - 1.0f / pixel_ratio()) > 1e-4f)
211 reload_font();
212 ImGui::NewFrame();
213
214 Viewer::pre_draw();
215 draw_gui(); // user widgets are emitted here (between NewFrame and Render)
216 // After Render(), ImGui produces triangle lists with a scissor rect per command.
217 const auto *data = ImGui::GetDrawData();
218 const ImVec2 scale = data->FramebufferScale, origin = data->DisplayPos;
219 int fw = 0, fh = 0;
220 framebuffer_size(fw, fh);
221 std::vector<graphics::DrawCommand> commands;
222 for (int n = 0; n < data->CmdListsCount; ++n) {
223 const auto *list = data->CmdLists[n];
224 for (const auto &draw : list->CmdBuffer) {
225 if (draw.UserCallback) {
226 if (draw.UserCallback != ImDrawCallback_ResetRenderState)
227 draw.UserCallback(list, &draw);
228 continue;
229 }
230 if (!draw.ElemCount)
231 continue;
232 // Convert ImGui's scissor rectangle to framebuffer pixels; this becomes the
233 // viewport for the overlay command so widgets clip correctly.
234 const int x = std::max(0, int(std::floor((draw.ClipRect.x - origin.x) * scale.x)));
235 const int y = std::max(0, int(std::floor((draw.ClipRect.y - origin.y) * scale.y)));
236 const int right = std::min(fw, int(std::ceil((draw.ClipRect.z - origin.x) * scale.x)));
237 const int bottom = std::min(fh, int(std::ceil((draw.ClipRect.w - origin.y) * scale.y)));
238 if (right <= x || bottom <= y)
239 continue;
240 if (draw.GetTexID() != ImGui::GetIO().Fonts->TexID)
241 throw std::logic_error("this tutorial supports the ImGui font atlas texture only");
242 // Expand the indexed triangles into a plain vertex list, converting ImGui's
243 // packed RGBA color and pixel-space position into Easy3D vertex attributes.
244 std::vector<graphics::Vertex> vertices;
245 vertices.reserve(draw.ElemCount);
246 for (unsigned i = 0; i < draw.ElemCount; ++i) {
247 const auto &source = list->VtxBuffer[list->IdxBuffer[draw.IdxOffset + i] + draw.VtxOffset];
249 v.position =
250 vec3((source.pos.x - origin.x) * scale.x - x, (source.pos.y - origin.y) * scale.y - y, 0);
251 v.texcoord = vec2(source.uv.x, source.uv.y);
252 v.color = vec4(float((source.col >> IM_COL32_R_SHIFT) & 255) / 255,
253 float((source.col >> IM_COL32_G_SHIFT) & 255) / 255,
254 float((source.col >> IM_COL32_B_SHIFT) & 255) / 255,
255 float((source.col >> IM_COL32_A_SHIFT) & 255) / 255);
256 vertices.push_back(v);
257 }
258 graphics::DrawCommand command;
259 command.overlay = true; // drawn on top of the 3D scene, in screen space
260 command.texture = font_image_;
261 command.viewport = ivec4(x, y, right - x, bottom - y);
262 command.model_view_projection = graphics::screen_space_projection(right - x, bottom - y);
263 command.geometry = std::make_shared<graphics::Geometry>(std::move(vertices));
264 commands.push_back(std::move(command));
265 }
266 }
267 // Hand the translated GUI geometry to the viewer for compositing this frame.
268 set_overlays(std::move(commands), true);
269}
270
271// The actual widgets. In immediate mode this runs every frame: each MenuItem both draws
272// itself and returns true when clicked, so the action is invoked right here.
273void ViewerImGui::draw_gui() {
274 ImGui::SetCurrentContext(context_);
275 static bool show_about = false;
276 if (show_about) {
277 int w = 0, h = 0;
278 viewer_size(w, h);
279 ImGui::SetNextWindowPos(ImVec2(static_cast<float>(w) * 0.5f, static_cast<float>(h) * 0.5f),
280 ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
281 ImGui::Begin("About Easy3D ImGui Viewer", &show_about, ImGuiWindowFlags_NoResize);
282 ImGui::Text("This viewer shows how to use ImGui for GUI creation and event handling");
283 ImGui::Separator();
284 ImGui::Text("\n" "Liangliang Nan\n" "liangliang.nan@gmail.com\n" "https://3d.bk.tudelft.nl/liangliang/\n");
285 ImGui::End();
286 }
287
288 // Keep the horizontal padding, but never shrink the vertical one below the style's
289 // display safe area: BeginMainMenuBar() moves its labels down by
290 // max(DisplaySafeAreaPadding.y - FramePadding.y, 0) inside a bar whose height is
291 // FontSize + 2*FramePadding.y, so a smaller padding clips the text.
292 ImGui::PushStyleVar(ImGuiStyleVar_FramePadding,
293 ImVec2(5, ImGui::GetStyle().DisplaySafeAreaPadding.y));
294 // The main menu bar spans the top of the window; its height is recorded for layout.
295 if (ImGui::BeginMainMenuBar()) {
296 draw_menu_file();
297 draw_menu_view();
298
299 if (ImGui::BeginMenu("Help")) {
300 ImGui::MenuItem("About", nullptr, &show_about);
301 ImGui::EndMenu();
302 }
303 menu_height_ = ImGui::GetWindowHeight();
304 ImGui::EndMainMenuBar();
305 }
306 ImGui::PopStyleVar();
307
308 ImGui::Render();
309}
310
311// The "File" menu: each MenuItem invokes the matching base-Viewer action when clicked.
312void ViewerImGui::draw_menu_file() {
313 if (ImGui::BeginMenu("File")) {
314 if (ImGui::MenuItem("Open", "Ctrl+O"))
315 open();
316 if (ImGui::MenuItem("Save As...", "Ctrl+S"))
317 save();
318
319 ImGui::Separator();
320 if (ImGui::MenuItem("Quit", "Alt+F4"))
321 request_close();
322
323 ImGui::EndMenu();
324 }
325}
326
327// The "View" menu: exposes the viewer's snapshot action.
328void ViewerImGui::draw_menu_view() {
329 if (ImGui::BeginMenu("View")) {
330 if (ImGui::MenuItem("Snapshot", nullptr))
331 snapshot();
332
333 ImGui::EndMenu();
334 }
335}
336
337// \endcond
Complete backend-independent description of a draw operation.
Definition render_device.h:219
Texture addressing and filtering configuration.
Definition render_device.h:165
TextureFilter filter
Interpolation used when sampling between texels.
Definition render_device.h:169
Per-vertex data consumed by a draw command.
Definition render_device.h:91
vec3 position
Position in geometry-local coordinates.
Definition render_device.h:93
vec2 texcoord
Texture coordinate.
Definition render_device.h:99
vec4 color
RGBA vertex color.
Definition render_device.h:97
See also
Viewer, ViewerImGui, Tutorial_201_Viewer_default