0


【我的渲染技术进阶之旅】关于C++轻量级界面开发框架Dear ImGui介绍

文章目录

一、怎么知道ImGui的

在学习了一段时间OpenGL,和看过使用OpenGL相关的渲染框架之后,发现Imgui的身影基本上都存在,因此有必要了解一下Imgui库。

1.1 Filament中有使用ImGui

当我在研究Filament项目的时候,发现有使用ImGUI
在这里插入图片描述

在这里插入图片描述
对应的代码如下:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

1.2 其他很多渲染框架都有使用ImGui

  • Easy3D在这里插入图片描述 效果图在这里插入图片描述
  • erhe在这里插入图片描述 效果图在这里插入图片描述
  • 其他 还有很多初学OpenGL的读者,都使用Imgui来搭建自己的渲染编辑器。

二、ImGui介绍

2.1 ImGui风格

imgui是目前最流行的ui库,它长这样。
在这里插入图片描述

你能在各种开源引擎、工具、软件看见它,它的风格比较特别,让你一眼就知道,这个软件的界面是imgui做的。
在这里插入图片描述

2.2 Imgui介绍

2.2.1 Imgui简介

Dear ImGui 是一个 用于C ++的无膨胀图形用户界面库. 它输出优化的顶点缓冲区,您可以随时在启用3D管线的应用程序中进行渲染。 它快速,可移植,与渲染器无关并且是独立的(无外部依赖性)。

Dear ImGui 被设计成 启用快速迭代 并 赋权程序员 以创建 内容创建工具和可视化/调试工具 (与普通最终用户的UI相对). 它有利于实现该目标的简单性和生产率,并且缺少通常在更高级的库中发现的某些功能。

Dear ImGui 特别适合集成到游戏引擎(用于工具),实时3D应用程序,全屏应用程序,嵌入式应用程序或非标准操作系统功能的控制台平台上的任何应用程序中。

2.2.2 Imgui用法

Dear ImGui 的核心是独立于几个与平台无关的文件 您可以轻松地在应用程序/引擎中进行编译。 它们都是存储库根文件夹中的所有文件(imgui.cpp,imgui.h,imgui_demo.cpp,imgui_draw.cpp等)。

不需要特定的构建过程. 您可以将.cpp文件添加到现有项目中。

您将需要一个后端来将Dear ImGui集成到您的应用程序中。 后端将鼠标/键盘/游戏板输入和各种设置传递给Dear ImGui,并负责渲染最终的顶点。

各种图形API和渲染平台的后端 提供在 backends/ 文件夹, 以及examples/ 文件夹. 有关详细信息,请参见本文档的集成部分。您也可以创建自己的backends后端。在您可以渲染纹理三角形的任何地方,您都可以渲染亲爱的Imgui。

在您的应用程序中设置 Dear ImGui 后,您可以在程序循环中的任何地方使用它:

  • 代码片段1:
ImGui::Text("Hello, world %d",123);if(ImGui::Button("Save"))MySaveFunction();ImGui::InputText("string", buf,IM_ARRAYSIZE(buf));ImGui::SliderFloat("float",&f,0.0f,1.0f);
  • 渲染结果:在这里插入图片描述在这里插入图片描述
  • 代码片段2:
// Create a window called "My First Tool", with a menu bar.ImGui::Begin("My First Tool",&my_tool_active, ImGuiWindowFlags_MenuBar);if(ImGui::BeginMenuBar()){if(ImGui::BeginMenu("File")){if(ImGui::MenuItem("Open..","Ctrl+O")){/* Do stuff */}if(ImGui::MenuItem("Save","Ctrl+S")){/* Do stuff */}if(ImGui::MenuItem("Close","Ctrl+W")){ my_tool_active =false;}ImGui::EndMenu();}ImGui::EndMenuBar();}// Edit a color stored as 4 floatsImGui::ColorEdit4("Color", my_color);// Generate samples and plot themfloat samples[100];for(int n =0; n <100; n++)
    samples[n]=sinf(n *0.2f+ImGui::GetTime()*1.5f);ImGui::PlotLines("Samples", samples,100);// Display contents in a scrolling regionImGui::TextColored(ImVec4(1,1,0,1),"Important Stuff");ImGui::BeginChild("Scrolling");for(int n =0; n <50; n++)ImGui::Text("%04d: Some text", n);ImGui::EndChild();ImGui::End();
  • 渲染结果:在这里插入图片描述 Dear ImGui 允许您创建复杂的工具以及非常短暂的工具。在生命周期短的极端情况下:使用现代编译器的 Edit&Continue(热代码重新加载)功能,您可以添加一些小部件以在应用程序运行时调整变量,并在一分钟后删除代码! Dear ImGui 不仅仅用于调整值。您可以使用它来通过发出文本命令来跟踪正在运行的算法。您可以将它与您自己的反射数据一起使用,以实时浏览您的数据集。您可以使用它来公开引擎中子系统的内部结构,创建记录器、检查工具、分析器、调试器、整个游戏制作编辑器/框架等。

2.2.3 Demo示例

调用

ImGui :: ShowDemoWindow()

函数将创建一个演示窗口,其中展示了各种功能和示例。 该代码始终可在

imgui_demo.cpp

中参考。

在这里插入图片描述

2.2.4 集成

在大多数平台上和使用C ++时, 您应该可以使用imgui_impl_xxxx后端的组合而无需进行修改 (e.g.

imgui_impl_win32.cpp

+

imgui_impl_dx11.cpp

). 如果您的引擎支持多个平台,请考虑使用更多的imgui_impl_xxxx文件,而不是重写它们:对您来说这将减少工作量,您可以立即运行Dear ImGui。 如果愿意,您可以_later_决定使用自定义引擎功能重写自定义后端。

将Dear ImGui集成到您的自定义引擎中只需1)连接鼠标/键盘/游戏手柄输入2)将一个纹理上载到GPU /渲染引擎3)提供可绑定纹理并渲染纹理三角形的渲染功能。 The examples/文件夹中填充了执行此操作的应用程序。 如果您是一位熟练的程序员,熟悉这些概念,则将您花费不到两个小时的时间将Dear ImGui集成到您的自定义引擎中. Make sure to spend time reading the FAQ, comments, and some of the examples/ application!

官方维护的后端/绑定(在存储库中):

  • 渲染器:DirectX9,DirectX10,DirectX11,DirectX12,OpenGL(旧版),OpenGL3 / ES / ES2(现代),Vulkan,Metal。
  • 平台:GLFW,SDL2,Win32,Glut,OSX。
  • 框架:Emscripten,Allegro5,Marmalade。

第三方库 backends/bindings wiki page:

  • 语言:C, C# and: Beef, ChaiScript, Crystal, D, Go, Haskell, Haxe/hxcpp, Java, JavaScript, Julia, Kotlin, Lua, Odin, Pascal, PureBasic, Python, Ruby, Rust, Swift …
  • 框架:AGS/Adventure Game Studio, Amethyst, bsf, Cinder, Cocos2d-x, Diligent Engine, Flexium, GML/Game Maker Studio2, Godot, GTK3+OpenGL3, Irrlicht Engine, LÖVE+LUA, Magnum, NanoRT, nCine, Nim Game Lib, Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, Photoshop, px_render, Qt/QtDirect3D, SFML, Sokol, Unity, Unreal Engine 4, vtk, Win32 GDI, WxWidgets.。
  • 请注意,C绑定(cimgui)是自动生成的,您可以使用其json / lua输出生成其他语言的绑定。

Useful widgets and extensions wiki page:

  • 文本编辑器,节点编辑器,时间线编辑器,绘图,软件渲染器,远程网络访问,内存编辑器,小控件等。

另请参阅Wiki,以获取更多链接和想法。

2.2.5 更多案例

有关使用Dear ImGui的更多用户提交的项目的屏幕截图,请查看 Gallery Threads!

有关第三方窗口小部件和扩展的列表,请查看 Useful Widgets wiki 页面.

2.3 查看Imgui实例源代码

打开examples/imgui_examples.sln,
在这里插入图片描述

2.3.1 运行demo

example_glfw_opengl3

设为启动项目
在这里插入图片描述

然后运行程序,弹出一个窗口,如下所示:
在这里插入图片描述

  • 基本控件:Label、Text、CheckBox、Slider在这里插入图片描述
  • 窗体控件:树形控件、图片控件、ComboBox、列表控件、菜单栏等在这里插入图片描述

根据官方提供的demo来看,基本满足开发要求。

2.3.2 项目结构分析

example_glfw_opengl3

项目结构如下

在这里插入图片描述

  • sources目录下就是后端代码。
  • imgui_impl_glfw.cpp 负责使用glfw创建Window和处理IO。
  • imgui_impl_opengl3.cpp负责处理渲染相关事情,可以看到只需要实现几个接口,就可以将imgui接入到自己的引擎项目中

2.3.3 示例源码分析

代码并不多,分为以下几个步骤:

  1. 初始化glfw 创建window
  2. 初始化imgui
  3. 初始化imgui后端
  4. 主循环,在每一帧里创建GUI并渲染
// Dear ImGui: standalone example application for GLFW + OpenGL 3, using programmable pipeline// (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.// Read online: https://github.com/ocornut/imgui/tree/master/docs#include"imgui.h"#include"imgui_impl_glfw.h"#include"imgui_impl_opengl3.h"#include<stdio.h>#defineGL_SILENCE_DEPRECATION#ifdefined(IMGUI_IMPL_OPENGL_ES2)#include<GLES2/gl2.h>#endif#include<GLFW/glfw3.h>// Will drag system OpenGL headers// [Win32] Our example includes a copy of glfw3.lib pre-compiled with VS2010 to maximize ease of testing and compatibility with old VS compilers.// To link with VS2010-era libraries, VS2015+ requires linking with legacy_stdio_definitions.lib, which we do using this pragma.// Your own project should not be affected, as you are likely to link with a newer binary of GLFW that is adequate for your version of Visual Studio.#ifdefined(_MSC_VER)&&(_MSC_VER >=1900)&&!defined(IMGUI_DISABLE_WIN32_FUNCTIONS)#pragmacomment(lib,"legacy_stdio_definitions")#endifstaticvoidglfw_error_callback(int error,constchar* description){fprintf(stderr,"Glfw Error %d: %s\n", error, description);}intmain(int,char**){// 1. 初始化glfw 创建window// Setup windowglfwSetErrorCallback(glfw_error_callback);if(!glfwInit())return1;// Decide GL+GLSL versions#ifdefined(IMGUI_IMPL_OPENGL_ES2)// GL ES 2.0 + GLSL 100constchar* glsl_version ="#version 100";glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,2);glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,0);glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);#elifdefined(__APPLE__)// GL 3.2 + GLSL 150constchar* glsl_version ="#version 150";glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,2);glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);// 3.2+ onlyglfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);// Required on Mac#else// GL 3.0 + GLSL 130constchar* glsl_version ="#version 130";glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,0);//glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);  // 3.2+ only//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);            // 3.0+ only#endif// Create window with graphics context
    GLFWwindow* window =glfwCreateWindow(1280,720,"Dear ImGui GLFW+OpenGL3 example",NULL,NULL);if(window ==NULL)return1;glfwMakeContextCurrent(window);// 开启垂直同步glfwSwapInterval(1);// Enable vsync// 2. 初始化imgui// Setup Dear ImGui contextIMGUI_CHECKVERSION();ImGui::CreateContext();
    ImGuiIO& io =ImGui::GetIO();(void)io;//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;     // Enable Keyboard Controls//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;      // Enable Gamepad Controls// Setup Dear ImGui styleImGui::StyleColorsDark();//ImGui::StyleColorsLight();// 3. 初始化imgui后端// Setup Platform/Renderer backendsImGui_ImplGlfw_InitForOpenGL(window,true);ImGui_ImplOpenGL3_Init(glsl_version);// Load Fonts// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.// - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.// - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).// - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.// - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.// - Read 'docs/FONTS.md' for more instructions and details.// - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !//io.Fonts->AddFontDefault();//io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f);//io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);//ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());//IM_ASSERT(font != NULL);// Our statebool show_demo_window =true;bool show_another_window =false;
    ImVec4 clear_color =ImVec4(0.45f,0.55f,0.60f,1.00f);// 4. 主循环,在每一帧里创建GUI并渲染// Main loopwhile(!glfwWindowShouldClose(window)){// Poll and handle events (inputs, window resize, etc.)// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.glfwPollEvents();// 开始新的一帧// Start the Dear ImGui frameImGui_ImplOpenGL3_NewFrame();ImGui_ImplGlfw_NewFrame();ImGui::NewFrame();// 1. 显示大的demo窗口// 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).if(show_demo_window)ImGui::ShowDemoWindow(&show_demo_window);// 2. 创建小的demo窗口,这里可以熟悉下按钮、选中框等的绘制// 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.{staticfloat f =0.0f;staticint counter =0;ImGui::Begin("Hello, world!");// Create a window called "Hello, world!" and append into it.ImGui::Text("This is some useful text.");// Display some text (you can use a format strings too)ImGui::Checkbox("Demo Window",&show_demo_window);// Edit bools storing our window open/close stateImGui::Checkbox("Another Window",&show_another_window);ImGui::SliderFloat("float",&f,0.0f,1.0f);// Edit 1 float using a slider from 0.0f to 1.0fImGui::ColorEdit3("clear color",(float*)&clear_color);// Edit 3 floats representing a colorif(ImGui::Button("Button"))// Buttons return true when clicked (most widgets return true when edited/activated)
                counter++;ImGui::SameLine();ImGui::Text("counter = %d", counter);ImGui::Text("Application average %.3f ms/frame (%.1f FPS)",1000.0f/ImGui::GetIO().Framerate,ImGui::GetIO().Framerate);ImGui::End();}// 3. 创建一个窗口 里面放个按钮// 3. Show another simple window.if(show_another_window){ImGui::Begin("Another Window",&show_another_window);// Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)ImGui::Text("Hello from another window!");if(ImGui::Button("Close Me"))
                show_another_window =false;ImGui::End();}// 渲染// RenderingImGui::Render();int display_w, display_h;glfwGetFramebufferSize(window,&display_w,&display_h);glViewport(0,0, display_w, display_h);glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);glClear(GL_COLOR_BUFFER_BIT);ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());glfwSwapBuffers(window);}// CleanupImGui_ImplOpenGL3_Shutdown();ImGui_ImplGlfw_Shutdown();ImGui::DestroyContext();glfwDestroyWindow(window);glfwTerminate();return0;}
  • 小窗口在这里插入图片描述
  • 大窗口

大窗口使用

ImGui::ShowDemoWindow(&show_demo_window);

代码在

imgui_impl_opengl3.cpp

中实现,比较复杂。

下面列举几个画面即可:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

三、参考链接

四、总结

大家看完此篇文章之后,就会发现ImGui库还蛮简单入门的,快去实现你自己的渲染编辑器吧!

标签: c++ 开发语言 ui

本文转载自: https://blog.csdn.net/qq446282412/article/details/128630569
版权归原作者 字节卷动 所有, 如有侵权,请联系我们删除。

“【我的渲染技术进阶之旅】关于C++轻量级界面开发框架Dear ImGui介绍”的评论:

还没有评论