From d1840a21842f2d1eb67958053a1b594ac197b306 Mon Sep 17 00:00:00 2001 From: Nik Date: Thu, 10 Jul 2025 10:00:39 +0200 Subject: [PATCH] build: Update ImGui to v1.92.1 (#2325) Update ImGui to the latest version and rewrite most of the font handling code --- .gdbinit | 1 + lib/libimhex/include/hex/api/imhex_api.hpp | 20 +- .../include/hex/ui/imgui_imhex_extensions.h | 4 + lib/libimhex/source/api/imhex_api.cpp | 71 +- lib/libimhex/source/helpers/macos_menu.m | 1 + .../source/ui/imgui_imhex_extensions.cpp | 2 +- .../imgui/backend/include/imgui_impl_glfw.h | 12 +- .../backend/include/imgui_impl_opengl3.h | 12 +- .../imgui/backend/source/imgui_impl_glfw.cpp | 260 +- .../backend/source/imgui_impl_opengl3.cpp | 257 +- lib/third_party/imgui/cimgui/include/cimgui.h | 1212 ++++-- .../imgui/cimgui/source/cimgui.cpp | 968 ++++- lib/third_party/imgui/imgui/include/imgui.h | 841 ++-- .../imgui/imgui/include/imgui_internal.h | 381 +- .../imgui/imgui/include/imstb_textedit.h | 81 +- .../imgui/imgui/include/imstb_truetype.h | 4 +- .../include/misc/freetype/imgui_freetype.h | 68 +- lib/third_party/imgui/imgui/source/imgui.cpp | 1516 ++++++-- .../imgui/imgui/source/imgui_demo.cpp | 693 ++-- .../imgui/imgui/source/imgui_draw.cpp | 3436 ++++++++++++----- .../imgui/imgui/source/imgui_tables.cpp | 46 +- .../imgui/imgui/source/imgui_widgets.cpp | 347 +- .../source/misc/freetype/imgui_freetype.cpp | 1118 +++--- .../imgui/imnodes/source/imnodes.cpp | 2 +- lib/third_party/imgui/implot/include/implot.h | 6 +- .../imgui/implot/source/implot.cpp | 17 +- .../imgui/implot/source/implot_demo.cpp | 9 +- .../imgui/implot/source/implot_items.cpp | 10 +- .../imgui/implot3d/include/implot3d.h | 136 +- .../implot3d/include/implot3d_internal.h | 194 +- .../imgui/implot3d/source/implot3d.cpp | 1157 ++++-- .../imgui/implot3d/source/implot3d_demo.cpp | 399 +- .../imgui/implot3d/source/implot3d_items.cpp | 541 ++- .../imgui/implot3d/source/implot3d_meshes.cpp | 960 ++--- main/gui/source/init/splash_window.cpp | 1 - main/gui/source/window/macos_window.cpp | 1 + main/gui/source/window/window.cpp | 63 +- plugins/builtin/source/content/init_tasks.cpp | 1 - .../content/views/view_pattern_editor.cpp | 8 +- .../source/content/window_decoration.cpp | 2 +- plugins/fonts/CMakeLists.txt | 1 - plugins/fonts/include/font_atlas.hpp | 298 -- plugins/fonts/include/font_settings.hpp | 9 +- plugins/fonts/include/fonts/fonts.hpp | 6 +- plugins/fonts/source/font_loader.cpp | 263 -- plugins/fonts/source/font_settings.cpp | 16 +- plugins/fonts/source/fonts.cpp | 11 +- plugins/fonts/source/library_fonts.cpp | 108 +- plugins/ui/source/ui/hex_editor.cpp | 4 +- plugins/ui/source/ui/pattern_drawer.cpp | 12 +- 50 files changed, 9932 insertions(+), 5654 deletions(-) delete mode 100644 plugins/fonts/include/font_atlas.hpp delete mode 100644 plugins/fonts/source/font_loader.cpp diff --git a/.gdbinit b/.gdbinit index 3d20cea4a..b9d0711d7 100644 --- a/.gdbinit +++ b/.gdbinit @@ -7,6 +7,7 @@ skip -rfu ^ImGui:: # Trigger breakpoint when execution reaches triggerSafeShutdown() break triggerSafeShutdown +break __glibcxx_assert_fail # Print backtrace after execution jumped to an invalid address define fixbt diff --git a/lib/libimhex/include/hex/api/imhex_api.hpp b/lib/libimhex/include/hex/api/imhex_api.hpp index 613c26f3f..9aae1e67b 100644 --- a/lib/libimhex/include/hex/api/imhex_api.hpp +++ b/lib/libimhex/include/hex/api/imhex_api.hpp @@ -748,7 +748,7 @@ EXPORT_MODULE namespace hex { struct GlyphRange { u16 begin, end; }; struct Offset { float x, y; }; - struct Font { + struct MergeFont { std::string name; std::vector fontData; std::vector glyphRanges; @@ -758,10 +758,21 @@ EXPORT_MODULE namespace hex { std::optional defaultSize; }; + class Font { + public: + explicit Font(UnlocalizedString fontName); + + void push(float size = 0.0F) const; + void pop() const; + + [[nodiscard]] operator ImFont*() const; + private: + UnlocalizedString m_fontName; + }; + namespace impl { - const std::vector& getFonts(); - + const std::vector& getMergeFonts(); std::map& getFontDefinitions(); } @@ -779,6 +790,9 @@ EXPORT_MODULE namespace hex { void registerFont(const UnlocalizedString &fontName); ImFont* getFont(const UnlocalizedString &fontName); + void setDefaultFont(const Font& font); + const Font& getDefaultFont(); + float getDpi(); float pixelsToPoints(float pixels); float pointsToPixels(float points); diff --git a/lib/libimhex/include/hex/ui/imgui_imhex_extensions.h b/lib/libimhex/include/hex/ui/imgui_imhex_extensions.h index 5b3551441..3c469a715 100644 --- a/lib/libimhex/include/hex/ui/imgui_imhex_extensions.h +++ b/lib/libimhex/include/hex/ui/imgui_imhex_extensions.h @@ -99,6 +99,10 @@ namespace ImGuiExt { return m_textureId != 0; } + [[nodiscard]] operator ImTextureRef() const noexcept { + return m_textureId; + } + [[nodiscard]] operator ImTextureID() const noexcept { return m_textureId; } diff --git a/lib/libimhex/source/api/imhex_api.cpp b/lib/libimhex/source/api/imhex_api.cpp index 6ecfcdb16..cb15a51c4 100644 --- a/lib/libimhex/source/api/imhex_api.cpp +++ b/lib/libimhex/source/api/imhex_api.cpp @@ -1006,35 +1006,48 @@ namespace hex { namespace impl { - static AutoReset> s_fonts; - const std::vector& getFonts() { + static AutoReset> s_fonts; + const std::vector& getMergeFonts() { return *s_fonts; } - static float s_fontSize = DefaultFontSize; - void setFontSize(float size) { - s_fontSize = size; - } - - static AutoReset s_fontAtlas; - void setFontAtlas(ImFontAtlas* fontAtlas) { - s_fontAtlas = fontAtlas; - } - - static ImFont *s_boldFont = nullptr; - static ImFont *s_italicFont = nullptr; - void setFonts(ImFont *bold, ImFont *italic) { - s_boldFont = bold; - s_italicFont = italic; - } - static AutoReset> s_fontDefinitions; std::map& getFontDefinitions() { return *s_fontDefinitions; } + static AutoReset s_defaultFont; + } + Font::Font(UnlocalizedString fontName) : m_fontName(std::move(fontName)) { + Fonts::registerFont(m_fontName); + + if (impl::s_defaultFont == nullptr) + impl::s_defaultFont = this; + } + + void Font::push(float size) const { + auto font = getFont(m_fontName); + + if (size <= 0.0F) { + size = font->LegacySize; + } + + size *= System::getGlobalScale(); + + ImGui::PushFont(font, size); + } + + void Font::pop() const { + ImGui::PopFont(); + } + + Font::operator ImFont*() const { + return getFont(m_fontName); + } + + GlyphRange glyph(const char *glyph) { u32 codepoint; ImTextCharFromUtf8(&codepoint, glyph, nullptr); @@ -1075,7 +1088,7 @@ namespace hex { return; } - impl::s_fonts->emplace_back(Font { + impl::s_fonts->emplace_back(MergeFont { wolv::util::toUTF8String(path.filename()), fontFile.readVector(), glyphRanges, @@ -1087,7 +1100,7 @@ namespace hex { } void loadFont(const std::string &name, const std::span &data, const std::vector &glyphRanges, Offset offset, u32 flags, std::optional scalable, std::optional defaultSize) { - impl::s_fonts->emplace_back(Font { + impl::s_fonts->emplace_back(MergeFont { name, { data.begin(), data.end() }, glyphRanges, @@ -1098,14 +1111,6 @@ namespace hex { }); } - float getFontSize() { - return impl::s_fontSize; - } - - ImFontAtlas* getFontAtlas() { - return impl::s_fontAtlas; - } - void registerFont(const UnlocalizedString &fontName) { (*impl::s_fontDefinitions)[fontName] = nullptr; } @@ -1114,12 +1119,12 @@ namespace hex { return (*impl::s_fontDefinitions)[fontName]; } - ImFont* Bold() { - return impl::s_boldFont; + void setDefaultFont(const Font& font) { + impl::s_defaultFont = &font; } - ImFont* Italic() { - return impl::s_italicFont; + const Font& getDefaultFont() { + return **impl::s_defaultFont; } float getDpi() { diff --git a/lib/libimhex/source/helpers/macos_menu.m b/lib/libimhex/source/helpers/macos_menu.m index d1516d908..a8175bd95 100644 --- a/lib/libimhex/source/helpers/macos_menu.m +++ b/lib/libimhex/source/helpers/macos_menu.m @@ -32,6 +32,7 @@ static bool s_constructingMenu = false; static bool s_resetNeeded = true; void macosMenuBarInit(void) { + s_menuStackSize = 0; s_menuStack[0] = NSApp.mainMenu; s_menuStackSize += 1; diff --git a/lib/libimhex/source/ui/imgui_imhex_extensions.cpp b/lib/libimhex/source/ui/imgui_imhex_extensions.cpp index 8493d9329..712bbf35e 100644 --- a/lib/libimhex/source/ui/imgui_imhex_extensions.cpp +++ b/lib/libimhex/source/ui/imgui_imhex_extensions.cpp @@ -1019,7 +1019,7 @@ namespace ImGuiExt { std::string drawString; auto textEnd = text + strlen(text); for (auto wrapPos = text; wrapPos != textEnd;) { - wrapPos = ImGui::GetFont()->CalcWordWrapPositionA(1, wrapPos, textEnd, availableSpace.x * 0.8F); + wrapPos = ImGui::GetFont()->CalcWordWrapPosition(1, wrapPos, textEnd, availableSpace.x * 0.8F); drawString += std::string(text, wrapPos) + "\n"; text = wrapPos; } diff --git a/lib/third_party/imgui/backend/include/imgui_impl_glfw.h b/lib/third_party/imgui/backend/include/imgui_impl_glfw.h index 78776cd28..532372790 100644 --- a/lib/third_party/imgui/backend/include/imgui_impl_glfw.h +++ b/lib/third_party/imgui/backend/include/imgui_impl_glfw.h @@ -8,10 +8,13 @@ // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only). // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values are obsolete since 1.87 and not supported since 1.91.5] // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. -// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+). +// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. -// Issues: -// [ ] Platform: Multi-viewport: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor). +// [X] Multiple Dear ImGui contexts support. +// Missing features or Issues: +// [ ] Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround. +// [ ] Missing ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors. +// [ ] Multi-viewport: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor). // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. @@ -63,5 +66,8 @@ IMGUI_IMPL_API void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor* monitor, int // GLFW helpers IMGUI_IMPL_API void ImGui_ImplGlfw_Sleep(int milliseconds); +IMGUI_IMPL_API float ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window); +IMGUI_IMPL_API float ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor); + #endif // #ifndef IMGUI_DISABLE diff --git a/lib/third_party/imgui/backend/include/imgui_impl_opengl3.h b/lib/third_party/imgui/backend/include/imgui_impl_opengl3.h index ae718d8d7..9495d4e97 100644 --- a/lib/third_party/imgui/backend/include/imgui_impl_opengl3.h +++ b/lib/third_party/imgui/backend/include/imgui_impl_opengl3.h @@ -4,8 +4,9 @@ // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: -// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! -// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only). +// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! +// [x] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset) [Desktop OpenGL only!] +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. // About WebGL/ES: @@ -30,18 +31,19 @@ #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE -// Backend API +// Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = nullptr); IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown(); IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame(); IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data); // (Optional) Called by Init/NewFrame/Shutdown -IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateFontsTexture(); -IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = NULL to handle this manually. +IMGUI_IMPL_API void ImGui_ImplOpenGL3_UpdateTexture(ImTextureData* tex); + // Configuration flags to add in your imconfig file: //#define IMGUI_IMPL_OPENGL_ES2 // Enable ES 2 (Auto-detected on Emscripten) //#define IMGUI_IMPL_OPENGL_ES3 // Enable ES 3 (Auto-detected on iOS/Android) diff --git a/lib/third_party/imgui/backend/source/imgui_impl_glfw.cpp b/lib/third_party/imgui/backend/source/imgui_impl_glfw.cpp index 915fa16d3..beaf7d174 100644 --- a/lib/third_party/imgui/backend/source/imgui_impl_glfw.cpp +++ b/lib/third_party/imgui/backend/source/imgui_impl_glfw.cpp @@ -8,10 +8,13 @@ // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only). // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values are obsolete since 1.87 and not supported since 1.91.5] // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. -// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+). +// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. -// Issues: -// [ ] Platform: Multi-viewport: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor). +// [X] Multiple Dear ImGui contexts support. +// Missing features or Issues: +// [ ] Touch events are only correctly identified as Touch on Windows. This create issues with some interactions. GLFW doesn't provide a way to identify touch inputs from mouse inputs, we cannot call io.AddMouseSourceEvent() to identify the source. We provide a Windows-specific workaround. +// [ ] Missing ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress cursors. +// [ ] Multi-viewport: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor). // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. @@ -28,9 +31,16 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. +// 2025-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. +// 2025-06-18: Added support for multiple Dear ImGui contexts. (#8676, #8239, #8069) +// 2025-06-11: Added ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window) and ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor) helper to facilitate making DPI-aware apps. +// 2025-05-15: [Docking] Add Platform_GetWindowFramebufferScale() handler, to allow varying Retina display density on multiple monitors. +// 2025-04-26: [Docking] Disable multi-viewports under Wayland. (#8587) +// 2025-03-10: Map GLFW_KEY_WORLD_1 and GLFW_KEY_WORLD_2 into ImGuiKey_Oem102. +// 2025-03-03: Fixed clipboard handler assertion when using GLFW <= 3.2.1 compiled with asserts enabled. +// 2025-02-21: [Docking] Update monitors and work areas information every frame, as the later may change regardless of monitor changes. (#8415) // 2024-11-05: [Docking] Added Linux workaround for spurious mouse up events emitted while dragging and creating new viewport. (#3158, #7733, #7922) -// 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: +// 2024-08-22: Moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn // - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn @@ -97,6 +107,8 @@ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe #endif // GLFW @@ -120,12 +132,12 @@ // IMHEX PATCH END #ifndef _WIN32 #include // for usleep() +// IMHEX PATCH BEGIN +#include // for std::string_view +#include // for std::getenv() +// IMHEX PATCH END #endif - -#ifdef __linux__ -#include -#include -#endif +#include // for snprintf() #ifdef __EMSCRIPTEN__ #include @@ -172,6 +184,17 @@ static std::string clipboardContent; #define GLFW_HAS_GAMEPAD_API (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetGamepadState() new api #define GLFW_HAS_GETKEYNAME (GLFW_VERSION_COMBINED >= 3200) // 3.2+ glfwGetKeyName() #define GLFW_HAS_GETERROR (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetError() +#define GLFW_HAS_GETPLATFORM (GLFW_VERSION_COMBINED >= 3400) // 3.4+ glfwGetPlatform() + +// Map GLFWWindow* to ImGuiContext*. +// - Would be simpler if we could use glfwSetWindowUserPointer()/glfwGetWindowUserPointer(), but this is a single and shared resource. +// - Would be simpler if we could use e.g. std::map<> as well. But we don't. +// - This is not particularly optimized as we expect size to be small and queries to be rare. +struct ImGui_ImplGlfw_WindowToContext { GLFWwindow* Window; ImGuiContext* Context; }; +static ImVector g_ContextMap; +static void ImGui_ImplGlfw_ContextMap_Add(GLFWwindow* window, ImGuiContext* ctx) { g_ContextMap.push_back(ImGui_ImplGlfw_WindowToContext{ window, ctx }); } +static void ImGui_ImplGlfw_ContextMap_Remove(GLFWwindow* window) { for (ImGui_ImplGlfw_WindowToContext& entry : g_ContextMap) if (entry.Window == window) { g_ContextMap.erase_unsorted(&entry); return; } } +static ImGuiContext* ImGui_ImplGlfw_ContextMap_Get(GLFWwindow* window) { for (ImGui_ImplGlfw_WindowToContext& entry : g_ContextMap) if (entry.Window == window) return entry.Context; return nullptr; } // GLFW data enum GlfwClientApi @@ -183,6 +206,7 @@ enum GlfwClientApi struct ImGui_ImplGlfw_Data { + ImGuiContext* Context; GLFWwindow* Window; GlfwClientApi ClientApi; double Time; @@ -194,7 +218,7 @@ struct ImGui_ImplGlfw_Data GLFWwindow* KeyOwnerWindows[GLFW_KEY_LAST]; bool InstalledCallbacks; bool CallbacksChainForAllWindows; - bool WantUpdateMonitors; + char BackendPlatformName[32]; #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 const char* CanvasSelector; #endif @@ -222,10 +246,18 @@ struct ImGui_ImplGlfw_Data // (passing install_callbacks=false in ImGui_ImplGlfw_InitXXX functions), set the current dear imgui context and then call our callbacks. // - Otherwise we may need to store a GLFWWindow* -> ImGuiContext* map and handle this in the backend, adding a little bit of extra complexity to it. // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. +namespace ImGui { extern ImGuiIO& GetIO(ImGuiContext*); } static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData() { + // Get data for current context return ImGui::GetCurrentContext() ? (ImGui_ImplGlfw_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; } +static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData(GLFWwindow* window) +{ + // Get data for a given GLFW window, regardless of current context (since GLFW events are sent together) + ImGuiContext* ctx = ImGui_ImplGlfw_ContextMap_Get(window); + return (ImGui_ImplGlfw_Data*)ImGui::GetIO(ctx).BackendPlatformUserData; +} // Forward Declarations static void ImGui_ImplGlfw_UpdateMonitors(); @@ -233,6 +265,7 @@ static void ImGui_ImplGlfw_InitMultiViewportSupport(); static void ImGui_ImplGlfw_ShutdownMultiViewportSupport(); // Functions + static const char* ImGui_ImplGlfw_GetClipboardText(void* user_data) { // IMHEX PATCH BEGIN @@ -286,6 +319,8 @@ ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode) case GLFW_KEY_EQUAL: return ImGuiKey_Equal; case GLFW_KEY_LEFT_BRACKET: return ImGuiKey_LeftBracket; case GLFW_KEY_BACKSLASH: return ImGuiKey_Backslash; + case GLFW_KEY_WORLD_1: return ImGuiKey_Oem102; + case GLFW_KEY_WORLD_2: return ImGuiKey_Oem102; case GLFW_KEY_RIGHT_BRACKET: return ImGuiKey_RightBracket; case GLFW_KEY_GRAVE_ACCENT: return ImGuiKey_GraveAccent; case GLFW_KEY_CAPS_LOCK: return ImGuiKey_CapsLock; @@ -385,11 +420,9 @@ ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode) // X11 does not include current pressed/released modifier key in 'mods' flags submitted by GLFW // See https://github.com/ocornut/imgui/issues/6034 and https://github.com/glfw/glfw/issues/1630 -static void ImGui_ImplGlfw_UpdateKeyModifiers(GLFWwindow* window, int mods) +static void ImGui_ImplGlfw_UpdateKeyModifiers(ImGuiIO& io, GLFWwindow* window, int mods) { // IMHEX PATCH BEGIN - ImGuiIO& io = ImGui::GetIO(); - #ifdef __linux__ static bool isX11 = [] { const auto sessionType = std::getenv("XDG_SESSION_TYPE"); @@ -415,33 +448,31 @@ static void ImGui_ImplGlfw_UpdateKeyModifiers(GLFWwindow* window, int mods) // IMHEX PATCH END } -static bool ImGui_ImplGlfw_ShouldChainCallback(GLFWwindow* window) +static bool ImGui_ImplGlfw_ShouldChainCallback(ImGui_ImplGlfw_Data* bd, GLFWwindow* window) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); return bd->CallbacksChainForAllWindows ? true : (window == bd->Window); } void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackMousebutton != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); + if (bd->PrevUserCallbackMousebutton != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window)) bd->PrevUserCallbackMousebutton(window, button, action, mods); // Workaround for Linux: ignore mouse up events which are following an focus loss following a viewport creation if (bd->MouseIgnoreButtonUp && action == GLFW_RELEASE) return; - ImGui_ImplGlfw_UpdateKeyModifiers(window, mods); - - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(bd->Context); + ImGui_ImplGlfw_UpdateKeyModifiers(io, window, mods); if (button >= 0 && button < ImGuiMouseButton_COUNT) io.AddMouseButtonEvent(button, action == GLFW_PRESS); } void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackScroll != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); + if (bd->PrevUserCallbackScroll != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window)) bd->PrevUserCallbackScroll(window, xoffset, yoffset); #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 @@ -449,7 +480,7 @@ void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yo return; #endif - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(bd->Context); io.AddMouseWheelEvent((float)xoffset, (float)yoffset); } @@ -489,21 +520,21 @@ static int ImGui_ImplGlfw_TranslateUntranslatedKey(int key, int scancode) void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int keycode, int scancode, int action, int mods) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackKey != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); + if (bd->PrevUserCallbackKey != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window)) bd->PrevUserCallbackKey(window, keycode, scancode, action, mods); if (action != GLFW_PRESS && action != GLFW_RELEASE) return; - ImGui_ImplGlfw_UpdateKeyModifiers(window, mods); + ImGuiIO& io = ImGui::GetIO(bd->Context); + ImGui_ImplGlfw_UpdateKeyModifiers(io, window, mods); if (keycode >= 0 && keycode < IM_ARRAYSIZE(bd->KeyOwnerWindows)) bd->KeyOwnerWindows[keycode] = (action == GLFW_PRESS) ? window : nullptr; keycode = ImGui_ImplGlfw_TranslateUntranslatedKey(keycode, scancode); - ImGuiIO& io = ImGui::GetIO(); ImGuiKey imgui_key = ImGui_ImplGlfw_KeyToImGuiKey(keycode, scancode); io.AddKeyEvent(imgui_key, (action == GLFW_PRESS)); io.SetKeyEventNativeData(imgui_key, keycode, scancode); // To support legacy indexing (<1.87 user code) @@ -511,25 +542,25 @@ void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int keycode, int scancode, i void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackWindowFocus != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); + if (bd->PrevUserCallbackWindowFocus != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window)) bd->PrevUserCallbackWindowFocus(window, focused); // Workaround for Linux: when losing focus with MouseIgnoreButtonUpWaitForFocusLoss set, we will temporarily ignore subsequent Mouse Up events bd->MouseIgnoreButtonUp = (bd->MouseIgnoreButtonUpWaitForFocusLoss && focused == 0); bd->MouseIgnoreButtonUpWaitForFocusLoss = false; - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(bd->Context); io.AddFocusEvent(focused != 0); } void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackCursorPos != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); + if (bd->PrevUserCallbackCursorPos != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window)) bd->PrevUserCallbackCursorPos(window, x, y); - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(bd->Context); if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { int window_x, window_y; @@ -545,11 +576,11 @@ void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y) // so we back it up and restore on Leave/Enter (see https://github.com/ocornut/imgui/issues/4984) void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackCursorEnter != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); + if (bd->PrevUserCallbackCursorEnter != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window)) bd->PrevUserCallbackCursorEnter(window, entered); - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(bd->Context); if (entered) { bd->MouseWindow = window; @@ -565,32 +596,32 @@ void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered) void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackChar != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); + if (bd->PrevUserCallbackChar != nullptr && ImGui_ImplGlfw_ShouldChainCallback(bd, window)) bd->PrevUserCallbackChar(window, c); - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(bd->Context); io.AddInputCharacter(c); } void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor*, int) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - bd->WantUpdateMonitors = true; + // This function is technically part of the API even if we stopped using the callback, so leaving it around. } #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 -static EM_BOOL ImGui_ImplEmscripten_WheelCallback(int, const EmscriptenWheelEvent* ev, void*) +static EM_BOOL ImGui_ImplEmscripten_WheelCallback(int, const EmscriptenWheelEvent* ev, void* user_data) { // Mimic Emscripten_HandleWheel() in SDL. // Corresponding equivalent in GLFW JS emulation layer has incorrect quantizing preventing small values. See #6096 + ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)user_data; float multiplier = 0.0f; if (ev->deltaMode == DOM_DELTA_PIXEL) { multiplier = 1.0f / 100.0f; } // 100 pixels make up a step. else if (ev->deltaMode == DOM_DELTA_LINE) { multiplier = 1.0f / 3.0f; } // 3 lines make up a step. else if (ev->deltaMode == DOM_DELTA_PAGE) { multiplier = 80.0f; } // A page makes up 80 steps. float wheel_x = ev->deltaX * -multiplier; float wheel_y = ev->deltaY * -multiplier; - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(bd->Context); io.AddMouseWheelEvent(wheel_x, wheel_y); //IMGUI_DEBUG_LOG("[Emsc] mode %d dx: %.2f, dy: %.2f, dz: %.2f --> feed %.2f %.2f\n", (int)ev->deltaMode, ev->deltaX, ev->deltaY, ev->deltaZ, wheel_x, wheel_y); return EM_TRUE; @@ -603,7 +634,7 @@ static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wPara void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); IM_ASSERT(bd->InstalledCallbacks == false && "Callbacks already installed!"); IM_ASSERT(bd->Window == window); @@ -620,7 +651,7 @@ void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window) void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(window); IM_ASSERT(bd->InstalledCallbacks == true && "Callbacks not installed!"); IM_ASSERT(bd->Window == window); @@ -670,24 +701,40 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw // Setup backend capabilities flags ImGui_ImplGlfw_Data* bd = IM_NEW(ImGui_ImplGlfw_Data)(); + snprintf(bd->BackendPlatformName, sizeof(bd->BackendPlatformName), "imgui_impl_glfw (%d)", GLFW_VERSION_COMBINED); io.BackendPlatformUserData = (void*)bd; - io.BackendPlatformName = "imgui_impl_glfw"; + io.BackendPlatformName = bd->BackendPlatformName; io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) + + bool has_viewports = false; #ifndef __EMSCRIPTEN__ - io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional) + has_viewports = true; +#if GLFW_HAS_GETPLATFORM + if (glfwGetPlatform() == GLFW_PLATFORM_WAYLAND) + has_viewports = false; +#endif + if (has_viewports) + io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional) #endif #if GLFW_HAS_MOUSE_PASSTHROUGH || GLFW_HAS_WINDOW_HOVERED io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can call io.AddMouseViewportEvent() with correct data (optional) #endif + bd->Context = ImGui::GetCurrentContext(); bd->Window = window; bd->Time = 0.0; - bd->WantUpdateMonitors = true; + ImGui_ImplGlfw_ContextMap_Add(window, bd->Context); ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); - platform_io.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* text) { glfwSetClipboardString(NULL, text); }; - platform_io.Platform_GetClipboardTextFn = [](ImGuiContext*) { return glfwGetClipboardString(NULL); }; +#if GLFW_VERSION_COMBINED < 3300 + platform_io.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* text) { glfwSetClipboardString(ImGui_ImplGlfw_GetBackendData()->Window, text); }; + platform_io.Platform_GetClipboardTextFn = [](ImGuiContext*) { return glfwGetClipboardString(ImGui_ImplGlfw_GetBackendData()->Window); }; +#else + platform_io.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* text) { glfwSetClipboardString(nullptr, text); }; + platform_io.Platform_GetClipboardTextFn = [](ImGuiContext*) { return glfwGetClipboardString(nullptr); }; +#endif + #ifdef __EMSCRIPTEN__ platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplGlfw_EmscriptenOpenURL(url); return true; }; #endif @@ -749,11 +796,14 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw #else IM_UNUSED(main_viewport); #endif - ImGui_ImplGlfw_InitMultiViewportSupport(); + if (has_viewports) + ImGui_ImplGlfw_InitMultiViewportSupport(); // Windows: register a WndProc hook so we can intercept some messages. #ifdef _WIN32 - bd->PrevWndProc = (WNDPROC)::GetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC); + HWND hwnd = (HWND)main_viewport->PlatformHandleRaw; + ::SetPropA(hwnd, "IMGUI_BACKEND_DATA", bd); + bd->PrevWndProc = (WNDPROC)::GetWindowLongPtrW(hwnd, GWLP_WNDPROC); IM_ASSERT(bd->PrevWndProc != nullptr); ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc); #endif @@ -764,7 +814,7 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw #if EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 >= 34020240817 if (emscripten::glfw3::IsRuntimePlatformApple()) { - ImGui::GetIO().ConfigMacOSXBehaviors = true; + io.ConfigMacOSXBehaviors = true; // Due to how the browser (poorly) handles the Meta Key, this line essentially disables repeats when used. // This means that Meta + V only registers a single key-press, even if the keys are held. @@ -815,6 +865,7 @@ void ImGui_ImplGlfw_Shutdown() // Windows: restore our WndProc hook #ifdef _WIN32 ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + ::SetPropA((HWND)main_viewport->PlatformHandleRaw, "IMGUI_BACKEND_DATA", nullptr); ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)bd->PrevWndProc); bd->PrevWndProc = nullptr; #endif @@ -822,6 +873,7 @@ void ImGui_ImplGlfw_Shutdown() io.BackendPlatformName = nullptr; io.BackendPlatformUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad | ImGuiBackendFlags_PlatformHasViewports | ImGuiBackendFlags_HasMouseHoveredViewport); + ImGui_ImplGlfw_ContextMap_Remove(bd->Window); IM_DELETE(bd); } @@ -933,7 +985,7 @@ static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0 static void ImGui_ImplGlfw_UpdateGamepads() { ImGuiIO& io = ImGui::GetIO(); - if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. + if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs, but see #8075 return; io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; @@ -983,9 +1035,7 @@ static void ImGui_ImplGlfw_UpdateGamepads() static void ImGui_ImplGlfw_UpdateMonitors() { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); - bd->WantUpdateMonitors = false; int monitors_count = 0; GLFWmonitor** glfw_monitors = glfwGetMonitors(&monitors_count); @@ -1012,35 +1062,63 @@ static void ImGui_ImplGlfw_UpdateMonitors() monitor.WorkSize = ImVec2((float)w, (float)h); } #endif -#if GLFW_HAS_PER_MONITOR_DPI - // Warning: the validity of monitor DPI information on Windows depends on the application DPI awareness settings, which generally needs to be set in the manifest or at runtime. - float x_scale, y_scale; - glfwGetMonitorContentScale(glfw_monitors[n], &x_scale, &y_scale); - if (x_scale == 0.0f) + float scale = ImGui_ImplGlfw_GetContentScaleForMonitor(glfw_monitors[n]); + if (scale == 0.0f) continue; // Some accessibility applications are declaring virtual monitors with a DPI of 0, see #7902. - monitor.DpiScale = x_scale; -#endif + monitor.DpiScale = scale; monitor.PlatformHandle = (void*)glfw_monitors[n]; // [...] GLFW doc states: "guaranteed to be valid only until the monitor configuration changes" platform_io.Monitors.push_back(monitor); } } +// - On Windows the process needs to be marked DPI-aware!! SDL2 doesn't do it by default. You can call ::SetProcessDPIAware() or call ImGui_ImplWin32_EnableDpiAwareness() from Win32 backend. +// - Apple platforms use FramebufferScale so we always return 1.0f. +// - Some accessibility applications are declaring virtual monitors with a DPI of 0.0f, see #7902. We preserve this value for caller to handle. +float ImGui_ImplGlfw_GetContentScaleForWindow(GLFWwindow* window) +{ +#if GLFW_HAS_PER_MONITOR_DPI && !defined(__APPLE__) + float x_scale, y_scale; + glfwGetWindowContentScale(window, &x_scale, &y_scale); + return x_scale; +#else + IM_UNUSED(window); + return 1.0f; +#endif +} + +float ImGui_ImplGlfw_GetContentScaleForMonitor(GLFWmonitor* monitor) +{ +#if GLFW_HAS_PER_MONITOR_DPI && !defined(__APPLE__) + float x_scale, y_scale; + glfwGetMonitorContentScale(monitor, &x_scale, &y_scale); + return x_scale; +#else + IM_UNUSED(monitor); + return 1.0f; +#endif +} + +static void ImGui_ImplGlfw_GetWindowSizeAndFramebufferScale(GLFWwindow* window, ImVec2* out_size, ImVec2* out_framebuffer_scale) +{ + int w, h; + int display_w, display_h; + glfwGetWindowSize(window, &w, &h); + glfwGetFramebufferSize(window, &display_w, &display_h); + if (out_size != nullptr) + *out_size = ImVec2((float)w, (float)h); + if (out_framebuffer_scale != nullptr) + *out_framebuffer_scale = (w > 0 && h > 0) ? ImVec2((float)display_w / (float)w, (float)display_h / (float)h) : ImVec2(1.0f, 1.0f); +} + void ImGui_ImplGlfw_NewFrame() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplGlfw_InitForXXX()?"); - // Setup display size (every frame to accommodate for window resizing) - int w, h; - int display_w, display_h; - glfwGetWindowSize(bd->Window, &w, &h); - glfwGetFramebufferSize(bd->Window, &display_w, &display_h); - io.DisplaySize = ImVec2((float)w, (float)h); - if (w > 0 && h > 0) - io.DisplayFramebufferScale = ImVec2((float)display_w / (float)w, (float)display_h / (float)h); - if (bd->WantUpdateMonitors) - ImGui_ImplGlfw_UpdateMonitors(); + // Setup main viewport size (every frame to accommodate for window resizing) + ImGui_ImplGlfw_GetWindowSizeAndFramebufferScale(bd->Window, &io.DisplaySize, &io.DisplayFramebufferScale); + ImGui_ImplGlfw_UpdateMonitors(); // Setup time step // (Accept glfwGetTime() not returning a monotonically increasing value. Seems to happens on disconnecting peripherals and probably on VMs and Emscripten, see #6491, #6189, #6114, #3644) @@ -1105,7 +1183,7 @@ void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow*, const char* canvas_s // Register Emscripten Wheel callback to workaround issue in Emscripten GLFW Emulation (#6096) // We intentionally do not check 'if (install_callbacks)' here, as some users may set it to false and call GLFW callback themselves. // FIXME: May break chaining in case user registered their own Emscripten callback? - emscripten_set_wheel_callback(bd->CanvasSelector, nullptr, false, ImGui_ImplEmscripten_WheelCallback); + emscripten_set_wheel_callback(bd->CanvasSelector, bd, false, ImGui_ImplEmscripten_WheelCallback); } #elif defined(EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3) // When using --use-port=contrib.glfw3 for the GLFW implementation, you can override the behavior of this call @@ -1127,10 +1205,10 @@ void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow* window, const char* c // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first.. //-------------------------------------------------------------------------------------------------------- -// Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data. +// Helper structure we store in the void* PlatformUserData field of each ImGuiViewport to easily retrieve our backend data. struct ImGui_ImplGlfw_ViewportData { - GLFWwindow* Window; + GLFWwindow* Window; // Stored in ImGuiViewport::PlatformHandle bool WindowOwned; int IgnoreWindowPosEventFrame; int IgnoreWindowSizeEventFrame; @@ -1209,9 +1287,11 @@ static void ImGui_ImplGlfw_CreateWindow(ImGuiViewport* viewport) GLFWwindow* share_window = (bd->ClientApi == GlfwClientApi_OpenGL) ? bd->Window : nullptr; vd->Window = glfwCreateWindow((int)viewport->Size.x, (int)viewport->Size.y, "No Title Yet", nullptr, share_window); vd->WindowOwned = true; + ImGui_ImplGlfw_ContextMap_Add(vd->Window, bd->Context); viewport->PlatformHandle = (void*)vd->Window; #ifdef _WIN32 viewport->PlatformHandleRaw = glfwGetWin32Window(vd->Window); + ::SetPropA((HWND)viewport->PlatformHandleRaw, "IMGUI_BACKEND_DATA", bd); // IMHEX PATCH BEGIN // REASON: The patch with #include // #elif defined(__APPLE__) @@ -1252,11 +1332,11 @@ static void ImGui_ImplGlfw_DestroyWindow(ImGuiViewport* viewport) // Release any keys that were pressed in the window being destroyed and are still held down, // because we will not receive any release events after window is destroyed. - for (int i = 0; i < IM_ARRAYSIZE(bd->KeyOwnerWindows); i++) { + for (int i = 0; i < IM_ARRAYSIZE(bd->KeyOwnerWindows); i++) if (bd->KeyOwnerWindows[i] == vd->Window) ImGui_ImplGlfw_KeyCallback(vd->Window, i, 0, GLFW_RELEASE, 0); // Later params are only used for main viewport, on which this function is never called. - } + ImGui_ImplGlfw_ContextMap_Remove(vd->Window); glfwDestroyWindow(vd->Window); } vd->Window = nullptr; @@ -1280,12 +1360,10 @@ static void ImGui_ImplGlfw_ShowWindow(ImGuiViewport* viewport) ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); } - // GLFW hack: install hook for WM_NCHITTEST message handler -#if !GLFW_HAS_MOUSE_PASSTHROUGH && GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) + // GLFW hack: install WndProc for mouse source event and WM_NCHITTEST message handler. ::SetPropA(hwnd, "IMGUI_VIEWPORT", viewport); vd->PrevWndProc = (WNDPROC)::GetWindowLongPtrW(hwnd, GWLP_WNDPROC); ::SetWindowLongPtrW(hwnd, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc); -#endif #if !GLFW_HAS_FOCUS_ON_SHOW // GLFW hack: GLFW 3.2 has a bug where glfwShowWindow() also activates/focus the window. @@ -1329,7 +1407,7 @@ static ImVec2 ImGui_ImplGlfw_GetWindowSize(ImGuiViewport* viewport) static void ImGui_ImplGlfw_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) { ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData; -#if __APPLE__ && !GLFW_HAS_OSX_WINDOW_POS_FIX +#if defined(__APPLE__) && !GLFW_HAS_OSX_WINDOW_POS_FIX // Native OS windows are positioned from the bottom-left corner on macOS, whereas on other platforms they are // positioned from the upper-left corner. GLFW makes an effort to convert macOS style coordinates, however it // doesn't handle it when changing size. We are manually moving the window in order for changes of size to be based @@ -1343,6 +1421,14 @@ static void ImGui_ImplGlfw_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) glfwSetWindowSize(vd->Window, (int)size.x, (int)size.y); } +static ImVec2 ImGui_ImplGlfw_GetWindowFramebufferScale(ImGuiViewport* viewport) +{ + ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData; + ImVec2 framebuffer_scale; + ImGui_ImplGlfw_GetWindowSizeAndFramebufferScale(vd->Window, nullptr, &framebuffer_scale); + return framebuffer_scale; +} + static void ImGui_ImplGlfw_SetWindowTitle(ImGuiViewport* viewport, const char* title) { ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData; @@ -1441,6 +1527,7 @@ static void ImGui_ImplGlfw_InitMultiViewportSupport() platform_io.Platform_GetWindowPos = ImGui_ImplGlfw_GetWindowPos; platform_io.Platform_SetWindowSize = ImGui_ImplGlfw_SetWindowSize; platform_io.Platform_GetWindowSize = ImGui_ImplGlfw_GetWindowSize; + platform_io.Platform_GetWindowFramebufferScale = ImGui_ImplGlfw_GetWindowFramebufferScale; platform_io.Platform_SetWindowFocus = ImGui_ImplGlfw_SetWindowFocus; platform_io.Platform_GetWindowFocus = ImGui_ImplGlfw_GetWindowFocus; platform_io.Platform_GetWindowMinimized = ImGui_ImplGlfw_GetWindowMinimized; @@ -1484,7 +1571,9 @@ static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo() } static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); + ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)::GetPropA(hWnd, "IMGUI_BACKEND_DATA"); + ImGuiIO& io = ImGui::GetIO(bd->Context); + WNDPROC prev_wndproc = bd->PrevWndProc; ImGuiViewport* viewport = (ImGuiViewport*)::GetPropA(hWnd, "IMGUI_VIEWPORT"); if (viewport != NULL) @@ -1500,7 +1589,7 @@ static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wPara case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_RBUTTONUP: case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: case WM_MBUTTONUP: case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: case WM_XBUTTONUP: - ImGui::GetIO().AddMouseSourceEvent(GetMouseSourceFromMessageExtraInfo()); + io.AddMouseSourceEvent(GetMouseSourceFromMessageExtraInfo()); break; // We have submitted https://github.com/glfw/glfw/pull/1568 to allow GLFW to support "transparent inputs". @@ -1517,6 +1606,7 @@ static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wPara break; } #endif + default: break; } return ::CallWindowProcW(prev_wndproc, hWnd, msg, wParam, lParam); } diff --git a/lib/third_party/imgui/backend/source/imgui_impl_opengl3.cpp b/lib/third_party/imgui/backend/source/imgui_impl_opengl3.cpp index 6991e72ef..a8e384fb2 100644 --- a/lib/third_party/imgui/backend/source/imgui_impl_opengl3.cpp +++ b/lib/third_party/imgui/backend/source/imgui_impl_opengl3.cpp @@ -4,8 +4,9 @@ // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: -// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! -// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only). +// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! +// [x] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset) [Desktop OpenGL only!] +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. // About WebGL/ES: @@ -23,7 +24,12 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. +// 2025-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. +// 2025-06-11: OpenGL: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplOpenGL3_CreateFontsTexture() and ImGui_ImplOpenGL3_DestroyFontsTexture(). +// 2025-06-04: OpenGL: Made GLES 3.20 contexts not access GL_CONTEXT_PROFILE_MASK nor GL_PRIMITIVE_RESTART. (#8664) +// 2025-02-18: OpenGL: Lazily reinitialize embedded GL loader for when calling backend from e.g. other DLL boundaries. (#8406) +// 2024-10-07: OpenGL: Changed default texture sampler to Clamp instead of Repeat/Wrap. +// 2024-06-28: OpenGL: ImGui_ImplOpenGL3_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL3_DestroyFontsTexture(). (#7748) // 2024-05-07: OpenGL: Update loader for Linux to support EGL/GLVND. (#7562) // 2024-04-16: OpenGL: Detect ES3 contexts on desktop based on version string, to e.g. avoid calling glPolygonMode() on them. (#7447) // 2024-01-09: OpenGL: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" and variants, fixing regression on distros missing a symlink. @@ -53,7 +59,7 @@ // 2021-01-03: OpenGL: Backup, setup and restore GL_STENCIL_TEST state. // 2020-10-23: OpenGL: Backup, setup and restore GL_PRIMITIVE_RESTART state. // 2020-10-15: OpenGL: Use glGetString(GL_VERSION) instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x) -// 2020-09-17: OpenGL: Fix to avoid compiling/calling glBindSampler() on ES or pre 3.3 context which have the defines set by a loader. +// 2020-09-17: OpenGL: Fix to avoid compiling/calling glBindSampler() on ES or pre-3.3 context which have the defines set by a loader. // 2020-07-10: OpenGL: Added support for glad2 OpenGL loader. // 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX. // 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix. @@ -113,10 +119,12 @@ #define _CRT_SECURE_NO_WARNINGS #endif +// IMHEX PATCH BEGIN #if !defined(WINGDIAPI) #define WINGDIAPI extern "C" #define APIENTRY #endif +// IMHEX PATCH END #include "imgui.h" #ifndef IMGUI_DISABLE @@ -130,6 +138,7 @@ // Clang/GCC warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: ignore unknown flags #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness #pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used @@ -141,6 +150,7 @@ #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind #pragma GCC diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' #pragma GCC diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader) +#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when simplifying division / ..when changing X +- C1 cmp C2 to X cmp C2 -+ C1 #endif // GL includes @@ -168,9 +178,11 @@ // In the rest of your app/engine, you can use another loader of your choice (gl3w, glew, glad, glbinding, glext, glLoadGen, etc.). // If you happen to be developing a new feature for this backend (imgui_impl_opengl3.cpp): // - You may need to regenerate imgui_impl_opengl3_loader.h to add new symbols. See https://github.com/dearimgui/gl3w_stripped +// Typically you would run: python3 ./gl3w_gen.py --output ../imgui/backends/imgui_impl_opengl3_loader.h --ref ../imgui/backends/imgui_impl_opengl3.cpp ./extra_symbols.txt // - You can temporarily use an unstripped version. See https://github.com/dearimgui/gl3w_stripped/releases // Changes to this backend using new APIs should be accompanied by a regenerated stripped loader version. #define IMGL3W_IMPL +#define IMGUI_IMPL_OPENGL_LOADER_IMGL3W #include "imgui_impl_opengl3_loader.h" #endif @@ -230,7 +242,7 @@ struct ImGui_ImplOpenGL3_Data bool GlProfileIsES3; bool GlProfileIsCompat; GLint GlProfileMask; - GLuint FontTexture; + GLint MaxTextureSize; GLuint ShaderHandle; GLint AttribLocationTex; // Uniforms location GLint AttribLocationProjMtx; @@ -243,6 +255,7 @@ struct ImGui_ImplOpenGL3_Data bool HasPolygonMode; bool HasClipOrigin; bool UseBufferSubData; + ImVector TempBuffer; ImGui_ImplOpenGL3_Data() { memset((void*)this, 0, sizeof(*this)); } }; @@ -255,8 +268,8 @@ static ImGui_ImplOpenGL3_Data* ImGui_ImplOpenGL3_GetBackendData() } // Forward Declarations -static void ImGui_ImplOpenGL3_InitPlatformInterface(); -static void ImGui_ImplOpenGL3_ShutdownPlatformInterface(); +static void ImGui_ImplOpenGL3_InitMultiViewportSupport(); +static void ImGui_ImplOpenGL3_ShutdownMultiViewportSupport(); // OpenGL vertex attribute state (for ES 1.0 and ES 2.0 only) #ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY @@ -282,20 +295,31 @@ struct ImGui_ImplOpenGL3_VtxAttribState }; #endif -// Functions -bool ImGui_ImplOpenGL3_Init(const char* glsl_version) +// Not static to allow third-party code to use that if they want to (but undocumented) +bool ImGui_ImplOpenGL3_InitLoader(); +bool ImGui_ImplOpenGL3_InitLoader() { - ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); - // Initialize our loader -#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM) - if (imgl3wInit() != 0) +#ifdef IMGUI_IMPL_OPENGL_LOADER_IMGL3W + if (glGetIntegerv == nullptr && imgl3wInit() != 0) { fprintf(stderr, "Failed to initialize OpenGL loader!\n"); return false; } #endif + return true; +} + +// Functions +bool ImGui_ImplOpenGL3_Init(const char* glsl_version) +{ + ImGuiIO& io = ImGui::GetIO(); + IMGUI_CHECKVERSION(); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); + + // Initialize loader + if (!ImGui_ImplOpenGL3_InitLoader()) + return false; // Setup backend capabilities flags ImGui_ImplOpenGL3_Data* bd = IM_NEW(ImGui_ImplOpenGL3_Data)(); @@ -303,13 +327,14 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) io.BackendRendererName = "imgui_impl_opengl3"; // Query for GL version (e.g. 320 for GL 3.2) + const char* gl_version_str = (const char*)glGetString(GL_VERSION); #if defined(IMGUI_IMPL_OPENGL_ES2) // GLES 2 bd->GlVersion = 200; bd->GlProfileIsES2 = true; + IM_UNUSED(gl_version_str); #else // Desktop or GLES 3 - const char* gl_version_str = (const char*)glGetString(GL_VERSION); GLint major = 0; GLint minor = 0; glGetIntegerv(GL_MAJOR_VERSION, &major); @@ -317,11 +342,7 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) if (major == 0 && minor == 0) sscanf(gl_version_str, "%d.%d", &major, &minor); // Query GL_VERSION in desktop GL 2.x, the string will start with "." bd->GlVersion = (GLuint)(major * 100 + minor * 10); -#if defined(GL_CONTEXT_PROFILE_MASK) - if (bd->GlVersion >= 320) - glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &bd->GlProfileMask); - bd->GlProfileIsCompat = (bd->GlProfileMask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) != 0; -#endif + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &bd->MaxTextureSize); #if defined(IMGUI_IMPL_OPENGL_ES3) bd->GlProfileIsES3 = true; @@ -330,6 +351,12 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) bd->GlProfileIsES3 = true; #endif +#if defined(GL_CONTEXT_PROFILE_MASK) + if (!bd->GlProfileIsES3 && bd->GlVersion >= 320) + glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &bd->GlProfileMask); + bd->GlProfileIsCompat = (bd->GlProfileMask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) != 0; +#endif + bd->UseBufferSubData = false; /* // Query vendor to enable glBufferSubData kludge @@ -342,14 +369,18 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) #endif #ifdef IMGUI_IMPL_OPENGL_DEBUG - printf("GlVersion = %d, \"%s\"\nGlProfileIsCompat = %d\nGlProfileMask = 0x%X\nGlProfileIsES2 = %d, GlProfileIsES3 = %d\nGL_VENDOR = '%s'\nGL_RENDERER = '%s'\n", bd->GlVersion, gl_version_str, bd->GlProfileIsCompat, bd->GlProfileMask, bd->GlProfileIsES2, bd->GlProfileIsES3, (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER)); // [DEBUG] + printf("GlVersion = %d, \"%s\"\nGlProfileIsCompat = %d\nGlProfileMask = 0x%X\nGlProfileIsES2/IsEs3 = %d/%d\nGL_VENDOR = '%s'\nGL_RENDERER = '%s'\n", bd->GlVersion, gl_version_str, bd->GlProfileIsCompat, bd->GlProfileMask, bd->GlProfileIsES2, bd->GlProfileIsES3, (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER)); // [DEBUG] #endif #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET if (bd->GlVersion >= 320) io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. #endif - io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. + io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) + + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Renderer_TextureMaxWidth = platform_io.Renderer_TextureMaxHeight = (int)bd->MaxTextureSize; // Store GLSL version string so we can refer to it later in case we recreate shaders. // Note: GLSL version is NOT the same as GL version. Leave this to nullptr if unsure. @@ -390,8 +421,7 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) } #endif - if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) - ImGui_ImplOpenGL3_InitPlatformInterface(); + ImGui_ImplOpenGL3_InitMultiViewportSupport(); return true; } @@ -402,11 +432,11 @@ void ImGui_ImplOpenGL3_Shutdown() IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplOpenGL3_ShutdownPlatformInterface(); + ImGui_ImplOpenGL3_ShutdownMultiViewportSupport(); ImGui_ImplOpenGL3_DestroyDeviceObjects(); io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; - io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasViewports); + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures | ImGuiBackendFlags_RendererHasViewports); IM_DELETE(bd); } @@ -415,8 +445,11 @@ void ImGui_ImplOpenGL3_NewFrame() ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOpenGL3_Init()?"); + ImGui_ImplOpenGL3_InitLoader(); // Lazily init loader if not already done for e.g. DLL boundaries. + if (!bd->ShaderHandle) - ImGui_ImplOpenGL3_CreateDeviceObjects(); + if (!ImGui_ImplOpenGL3_CreateDeviceObjects()) + IM_ASSERT(0 && "ImGui_ImplOpenGL3_CreateDeviceObjects() failed!"); } // IMHEX PATCH BEGIN @@ -454,7 +487,7 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid glDisable(GL_STENCIL_TEST); glEnable(GL_SCISSOR_TEST); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART - if (bd->GlVersion >= 310) + if (!bd->GlProfileIsES3 && bd->GlVersion >= 310) glDisable(GL_PRIMITIVE_RESTART); #endif #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE @@ -535,8 +568,17 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) if (fb_width <= 0 || fb_height <= 0) return; + ImGui_ImplOpenGL3_InitLoader(); // Lazily init loader if not already done for e.g. DLL boundaries. + ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplOpenGL3_UpdateTexture(tex); + // Backup GL state GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture); glActiveTexture(GL_TEXTURE0); @@ -573,7 +615,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) GLboolean last_enable_stencil_test = glIsEnabled(GL_STENCIL_TEST); GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART - GLboolean last_enable_primitive_restart = (bd->GlVersion >= 310) ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE; + GLboolean last_enable_primitive_restart = (!bd->GlProfileIsES3 && bd->GlVersion >= 310) ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE; #endif // Setup desired GL state @@ -592,7 +634,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) // Render command lists for (int n = 0; n < draw_data->CmdListsCount; n++) { - const ImDrawList* cmd_list = draw_data->CmdLists[n]; + const ImDrawList* draw_list = draw_data->CmdLists[n]; // Upload vertex/index buffers // - OpenGL drivers are in a very sorry state nowadays.... @@ -602,8 +644,8 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) // - We are now back to using exclusively glBufferData(). So bd->UseBufferSubData IS ALWAYS FALSE in this code. // We are keeping the old code path for a while in case people finding new issues may want to test the bd->UseBufferSubData path. // - See https://github.com/ocornut/imgui/issues/4468 and please report any corruption issues. - const GLsizeiptr vtx_buffer_size = (GLsizeiptr)cmd_list->VtxBuffer.Size * (int)sizeof(ImDrawVert); - const GLsizeiptr idx_buffer_size = (GLsizeiptr)cmd_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx); + const GLsizeiptr vtx_buffer_size = (GLsizeiptr)draw_list->VtxBuffer.Size * (int)sizeof(ImDrawVert); + const GLsizeiptr idx_buffer_size = (GLsizeiptr)draw_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx); if (bd->UseBufferSubData) { if (bd->VertexBufferSize < vtx_buffer_size) @@ -616,18 +658,18 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) bd->IndexBufferSize = idx_buffer_size; GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, bd->IndexBufferSize, nullptr, GL_STREAM_DRAW)); } - GL_CALL(glBufferSubData(GL_ARRAY_BUFFER, 0, vtx_buffer_size, (const GLvoid*)cmd_list->VtxBuffer.Data)); - GL_CALL(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, idx_buffer_size, (const GLvoid*)cmd_list->IdxBuffer.Data)); + GL_CALL(glBufferSubData(GL_ARRAY_BUFFER, 0, vtx_buffer_size, (const GLvoid*)draw_list->VtxBuffer.Data)); + GL_CALL(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, idx_buffer_size, (const GLvoid*)draw_list->IdxBuffer.Data)); } else { - GL_CALL(glBufferData(GL_ARRAY_BUFFER, vtx_buffer_size, (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW)); - GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, idx_buffer_size, (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW)); + GL_CALL(glBufferData(GL_ARRAY_BUFFER, vtx_buffer_size, (const GLvoid*)draw_list->VtxBuffer.Data, GL_STREAM_DRAW)); + GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, idx_buffer_size, (const GLvoid*)draw_list->IdxBuffer.Data, GL_STREAM_DRAW)); } - for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++) { - const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; + const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback != nullptr) { // User callback, registered via ImDrawList::AddCallback() @@ -635,7 +677,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object); else - pcmd->UserCallback(cmd_list, pcmd); + pcmd->UserCallback(draw_list, pcmd); } else { @@ -692,7 +734,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) if (last_enable_stencil_test) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST); if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART - if (bd->GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); } + if (!bd->GlProfileIsES3 && bd->GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); } #endif #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE @@ -705,48 +747,82 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) (void)bd; // Not all compilation paths use this } -bool ImGui_ImplOpenGL3_CreateFontsTexture() +static void ImGui_ImplOpenGL3_DestroyTexture(ImTextureData* tex) { - ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); + GLuint gl_tex_id = (GLuint)(intptr_t)tex->TexID; + glDeleteTextures(1, &gl_tex_id); - // Build texture atlas - unsigned char* pixels; - int width, height; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (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. - - // Upload texture to graphics system - // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) - GLint last_texture; - GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture)); - GL_CALL(glGenTextures(1, &bd->FontTexture)); - GL_CALL(glBindTexture(GL_TEXTURE_2D, bd->FontTexture)); - GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); - GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); -#ifdef GL_UNPACK_ROW_LENGTH // Not on WebGL/ES - GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); -#endif - GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels)); - - // Store our identifier - io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture); - - // Restore state - GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture)); - - return true; + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->SetStatus(ImTextureStatus_Destroyed); } -void ImGui_ImplOpenGL3_DestroyFontsTexture() +void ImGui_ImplOpenGL3_UpdateTexture(ImTextureData* tex) { - ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); - if (bd->FontTexture) + if (tex->Status == ImTextureStatus_WantCreate) { - glDeleteTextures(1, &bd->FontTexture); - io.Fonts->SetTexID(0); - bd->FontTexture = 0; + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == 0 && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + const void* pixels = tex->GetPixels(); + GLuint gl_texture_id = 0; + + // Upload texture to graphics system + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) + GLint last_texture; + GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture)); + GL_CALL(glGenTextures(1, &gl_texture_id)); + GL_CALL(glBindTexture(GL_TEXTURE_2D, gl_texture_id)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); +#ifdef GL_UNPACK_ROW_LENGTH // Not on WebGL/ES + GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); +#endif + GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex->Width, tex->Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels)); + + // Store identifiers + tex->SetTexID((ImTextureID)(intptr_t)gl_texture_id); + tex->SetStatus(ImTextureStatus_OK); + + // Restore state + GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture)); } + else if (tex->Status == ImTextureStatus_WantUpdates) + { + // Update selected blocks. We only ever write to textures regions which have never been used before! + // This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region. + GLint last_texture; + GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture)); + + GLuint gl_tex_id = (GLuint)(intptr_t)tex->TexID; + GL_CALL(glBindTexture(GL_TEXTURE_2D, gl_tex_id)); +#if 0// GL_UNPACK_ROW_LENGTH // Not on WebGL/ES + GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, tex->Width)); + for (ImTextureRect& r : tex->Updates) + GL_CALL(glTexSubImage2D(GL_TEXTURE_2D, 0, r.x, r.y, r.w, r.h, GL_RGBA, GL_UNSIGNED_BYTE, tex->GetPixelsAt(r.x, r.y))); + GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); +#else + // GL ES doesn't have GL_UNPACK_ROW_LENGTH, so we need to (A) copy to a contiguous buffer or (B) upload line by line. + ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); + for (ImTextureRect& r : tex->Updates) + { + const int src_pitch = r.w * tex->BytesPerPixel; + bd->TempBuffer.resize(r.h * src_pitch); + char* out_p = bd->TempBuffer.Data; + for (int y = 0; y < r.h; y++, out_p += src_pitch) + memcpy(out_p, tex->GetPixelsAt(r.x, r.y + y), src_pitch); + IM_ASSERT(out_p == bd->TempBuffer.end()); + GL_CALL(glTexSubImage2D(GL_TEXTURE_2D, 0, r.x, r.y, r.w, r.h, GL_RGBA, GL_UNSIGNED_BYTE, bd->TempBuffer.Data)); + } +#endif + tex->SetStatus(ImTextureStatus_OK); + GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture)); // Restore state + } + else if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0) + ImGui_ImplOpenGL3_DestroyTexture(tex); } // If you get an error please report on github. You may try different GL context version or GLSL version. See GL<>GLSL version table at the top of this file. @@ -796,7 +872,7 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK - GLint last_pixel_unpack_buffer; + GLint last_pixel_unpack_buffer = 0; if (bd->GlVersion >= 210) { glGetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &last_pixel_unpack_buffer); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); } #endif #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY @@ -931,7 +1007,7 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() " Out_Color = Frag_Color;\n" " SRC1_Color = vec4(texture(Texture, Frag_UV.st).rgb * Frag_Color.aaa,1.0);\n" " }\n" - // IMHEX PATCH END + // IMHEX PATCH END "}\n"; // Select shaders matching our GLSL versions @@ -960,23 +1036,28 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() // Create shaders const GLchar* vertex_shader_with_version[2] = { bd->GlslVersionString, vertex_shader }; - GLuint vert_handle = glCreateShader(GL_VERTEX_SHADER); + GLuint vert_handle; + GL_CALL(vert_handle = glCreateShader(GL_VERTEX_SHADER)); glShaderSource(vert_handle, 2, vertex_shader_with_version, nullptr); glCompileShader(vert_handle); - CheckShader(vert_handle, "vertex shader"); + if (!CheckShader(vert_handle, "vertex shader")) + return false; const GLchar* fragment_shader_with_version[2] = { bd->GlslVersionString, fragment_shader }; - GLuint frag_handle = glCreateShader(GL_FRAGMENT_SHADER); + GLuint frag_handle; + GL_CALL(frag_handle = glCreateShader(GL_FRAGMENT_SHADER)); glShaderSource(frag_handle, 2, fragment_shader_with_version, nullptr); glCompileShader(frag_handle); - CheckShader(frag_handle, "fragment shader"); + if (!CheckShader(frag_handle, "fragment shader")) + return false; // Link bd->ShaderHandle = glCreateProgram(); glAttachShader(bd->ShaderHandle, vert_handle); glAttachShader(bd->ShaderHandle, frag_handle); glLinkProgram(bd->ShaderHandle); - CheckProgram(bd->ShaderHandle, "shader program"); + if (!CheckProgram(bd->ShaderHandle, "shader program")) + return false; glDetachShader(bd->ShaderHandle, vert_handle); glDetachShader(bd->ShaderHandle, frag_handle); @@ -993,8 +1074,6 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() glGenBuffers(1, &bd->VboHandle); glGenBuffers(1, &bd->ElementsHandle); - ImGui_ImplOpenGL3_CreateFontsTexture(); - // Restore modified GL state glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); @@ -1014,7 +1093,11 @@ void ImGui_ImplOpenGL3_DestroyDeviceObjects() if (bd->VboHandle) { glDeleteBuffers(1, &bd->VboHandle); bd->VboHandle = 0; } if (bd->ElementsHandle) { glDeleteBuffers(1, &bd->ElementsHandle); bd->ElementsHandle = 0; } if (bd->ShaderHandle) { glDeleteProgram(bd->ShaderHandle); bd->ShaderHandle = 0; } - ImGui_ImplOpenGL3_DestroyFontsTexture(); + + // Destroy all textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + ImGui_ImplOpenGL3_DestroyTexture(tex); } //-------------------------------------------------------------------------------------------------------- @@ -1034,13 +1117,13 @@ static void ImGui_ImplOpenGL3_RenderWindow(ImGuiViewport* viewport, void*) ImGui_ImplOpenGL3_RenderDrawData(viewport->DrawData); } -static void ImGui_ImplOpenGL3_InitPlatformInterface() +static void ImGui_ImplOpenGL3_InitMultiViewportSupport() { ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); platform_io.Renderer_RenderWindow = ImGui_ImplOpenGL3_RenderWindow; } -static void ImGui_ImplOpenGL3_ShutdownPlatformInterface() +static void ImGui_ImplOpenGL3_ShutdownMultiViewportSupport() { ImGui::DestroyPlatformWindows(); } diff --git a/lib/third_party/imgui/cimgui/include/cimgui.h b/lib/third_party/imgui/cimgui/include/cimgui.h index bdc7dac41..9b193273c 100644 --- a/lib/third_party/imgui/cimgui/include/cimgui.h +++ b/lib/third_party/imgui/cimgui/include/cimgui.h @@ -1,11 +1,14 @@ //This file is automatically generated by generator.lua from https://github.com/cimgui/cimgui -//based on imgui.h file version "1.91.0" 19100 from Dear ImGui https://github.com/ocornut/imgui +//based on imgui.h file version "1.92.0" 19200 from Dear ImGui https://github.com/ocornut/imgui //with imgui_internal.h api +//with imgui_freetype.h api //docking branch + #ifndef CIMGUI_INCLUDED #define CIMGUI_INCLUDED #include #include + #if defined _WIN32 || defined __CYGWIN__ #ifdef CIMGUI_NO_EXPORT #define API @@ -38,6 +41,12 @@ typedef unsigned __int64 ImU64; //typedef unsigned long long ImU64; #endif +#ifndef CIMGUI_DEFINE_ENUMS_AND_STRUCTS +#ifdef IMGUI_ENABLE_FREETYPE +#include "misc/freetype/imgui_freetype.h" +#endif +#endif + #ifdef CIMGUI_DEFINE_ENUMS_AND_STRUCTS @@ -50,10 +59,15 @@ typedef struct ImDrawListSplitter ImDrawListSplitter; typedef struct ImDrawVert ImDrawVert; typedef struct ImFont ImFont; typedef struct ImFontAtlas ImFontAtlas; -typedef struct ImFontBuilderIO ImFontBuilderIO; +typedef struct ImFontAtlasBuilder ImFontAtlasBuilder; +typedef struct ImFontAtlasRect ImFontAtlasRect; +typedef struct ImFontBaked ImFontBaked; typedef struct ImFontConfig ImFontConfig; typedef struct ImFontGlyph ImFontGlyph; typedef struct ImFontGlyphRangesBuilder ImFontGlyphRangesBuilder; +typedef struct ImFontLoader ImFontLoader; +typedef struct ImTextureData ImTextureData; +typedef struct ImTextureRect ImTextureRect; typedef struct ImColor ImColor; typedef struct ImGuiContext ImGuiContext; typedef struct ImGuiIO ImGuiIO; @@ -64,8 +78,8 @@ typedef struct ImGuiMultiSelectIO ImGuiMultiSelectIO; typedef struct ImGuiOnceUponAFrame ImGuiOnceUponAFrame; typedef struct ImGuiPayload ImGuiPayload; typedef struct ImGuiPlatformIO ImGuiPlatformIO; -typedef struct ImGuiPlatformMonitor ImGuiPlatformMonitor; typedef struct ImGuiPlatformImeData ImGuiPlatformImeData; +typedef struct ImGuiPlatformMonitor ImGuiPlatformMonitor; typedef struct ImGuiSelectionBasicStorage ImGuiSelectionBasicStorage; typedef struct ImGuiSelectionExternalStorage ImGuiSelectionExternalStorage; typedef struct ImGuiSelectionRequest ImGuiSelectionRequest; @@ -81,16 +95,20 @@ typedef struct ImGuiViewport ImGuiViewport; typedef struct ImGuiWindowClass ImGuiWindowClass; typedef struct ImBitVector ImBitVector; typedef struct ImRect ImRect; +typedef struct ImGuiTextIndex ImGuiTextIndex; typedef struct ImDrawDataBuilder ImDrawDataBuilder; +typedef struct ImFontAtlasPostProcessData ImFontAtlasPostProcessData; +typedef struct ImFontAtlasRectEntry ImFontAtlasRectEntry; typedef struct ImGuiBoxSelectState ImGuiBoxSelectState; typedef struct ImGuiColorMod ImGuiColorMod; typedef struct ImGuiContextHook ImGuiContextHook; -typedef struct ImGuiStyleVarInfo ImGuiStyleVarInfo; typedef struct ImGuiDataTypeInfo ImGuiDataTypeInfo; +typedef struct ImGuiDeactivatedItemData ImGuiDeactivatedItemData; typedef struct ImGuiDockContext ImGuiDockContext; typedef struct ImGuiDockRequest ImGuiDockRequest; typedef struct ImGuiDockNode ImGuiDockNode; typedef struct ImGuiDockNodeSettings ImGuiDockNodeSettings; +typedef struct ImGuiErrorRecoveryState ImGuiErrorRecoveryState; typedef struct ImGuiGroupData ImGuiGroupData; typedef struct ImGuiInputTextState ImGuiInputTextState; typedef struct ImGuiInputTextDeactivateData ImGuiInputTextDeactivateData; @@ -107,8 +125,8 @@ typedef struct ImGuiOldColumnData ImGuiOldColumnData; typedef struct ImGuiOldColumns ImGuiOldColumns; typedef struct ImGuiPopupData ImGuiPopupData; typedef struct ImGuiSettingsHandler ImGuiSettingsHandler; -typedef struct ImGuiStackSizes ImGuiStackSizes; typedef struct ImGuiStyleMod ImGuiStyleMod; +typedef struct ImGuiStyleVarInfo ImGuiStyleVarInfo; typedef struct ImGuiTabBar ImGuiTabBar; typedef struct ImGuiTabItem ImGuiTabItem; typedef struct ImGuiTable ImGuiTable; @@ -125,6 +143,8 @@ typedef struct ImGuiWindow ImGuiWindow; typedef struct ImGuiWindowDockStyle ImGuiWindowDockStyle; typedef struct ImGuiWindowTempData ImGuiWindowTempData; typedef struct ImGuiWindowSettings ImGuiWindowSettings; +typedef struct STB_TexteditState STB_TexteditState; +typedef struct stbrp_node stbrp_node; typedef struct ImVector_const_charPtr {int Size;int Capacity;const char** Data;} ImVector_const_charPtr; typedef unsigned int ImGuiID; @@ -145,10 +165,15 @@ struct ImDrawListSplitter; struct ImDrawVert; struct ImFont; struct ImFontAtlas; -struct ImFontBuilderIO; +struct ImFontAtlasBuilder; +struct ImFontAtlasRect; +struct ImFontBaked; struct ImFontConfig; struct ImFontGlyph; struct ImFontGlyphRangesBuilder; +struct ImFontLoader; +struct ImTextureData; +struct ImTextureRect; struct ImColor; struct ImGuiContext; struct ImGuiIO; @@ -159,8 +184,8 @@ struct ImGuiMultiSelectIO; struct ImGuiOnceUponAFrame; struct ImGuiPayload; struct ImGuiPlatformIO; -struct ImGuiPlatformMonitor; struct ImGuiPlatformImeData; +struct ImGuiPlatformMonitor; struct ImGuiSelectionBasicStorage; struct ImGuiSelectionExternalStorage; struct ImGuiSelectionRequest; @@ -183,6 +208,7 @@ typedef int ImGuiStyleVar; typedef int ImGuiTableBgTarget; typedef int ImDrawFlags; typedef int ImDrawListFlags; +typedef int ImFontFlags; typedef int ImFontAtlasFlags; typedef int ImGuiBackendFlags; typedef int ImGuiButtonFlags; @@ -210,11 +236,20 @@ typedef int ImGuiTableRowFlags; typedef int ImGuiTreeNodeFlags; typedef int ImGuiViewportFlags; typedef int ImGuiWindowFlags; -typedef void* ImTextureID; -typedef unsigned short ImDrawIdx; typedef unsigned int ImWchar32; typedef unsigned short ImWchar16; + +#ifdef IMGUI_USE_WCHAR32 +typedef ImWchar32 ImWchar; +#else typedef ImWchar16 ImWchar; +#endif +#ifdef IMGUI_USE_WCHAR32 +#define IM_UNICODE_CODEPOINT_MAX 0x10FFFF +#else +#define IM_UNICODE_CODEPOINT_MAX 0xFFFF +#endif + typedef ImS64 ImGuiSelectionUserData; typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData* data); typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); @@ -230,6 +265,13 @@ struct ImVec4 { float x, y, z, w; }; +typedef ImU64 ImTextureID; +typedef struct ImTextureRef ImTextureRef; +struct ImTextureRef +{ + ImTextureData* _TexData; + ImTextureID _TexID; +}; typedef enum { ImGuiWindowFlags_None = 0, ImGuiWindowFlags_NoTitleBar = 1 << 0, @@ -255,16 +297,16 @@ typedef enum { ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, ImGuiWindowFlags_NoDecoration = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse, ImGuiWindowFlags_NoInputs = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, + ImGuiWindowFlags_DockNodeHost = 1 << 23, ImGuiWindowFlags_ChildWindow = 1 << 24, ImGuiWindowFlags_Tooltip = 1 << 25, ImGuiWindowFlags_Popup = 1 << 26, ImGuiWindowFlags_Modal = 1 << 27, ImGuiWindowFlags_ChildMenu = 1 << 28, - ImGuiWindowFlags_DockNodeHost = 1 << 29, }ImGuiWindowFlags_; typedef enum { ImGuiChildFlags_None = 0, - ImGuiChildFlags_Border = 1 << 0, + ImGuiChildFlags_Borders = 1 << 0, ImGuiChildFlags_AlwaysUseWindowPadding = 1 << 1, ImGuiChildFlags_ResizeX = 1 << 2, ImGuiChildFlags_ResizeY = 1 << 3, @@ -281,6 +323,7 @@ typedef enum { ImGuiItemFlags_NoNavDefaultFocus = 1 << 2, ImGuiItemFlags_ButtonRepeat = 1 << 3, ImGuiItemFlags_AutoClosePopups = 1 << 4, + ImGuiItemFlags_AllowDuplicateId = 1 << 5, }ImGuiItemFlags_; typedef enum { ImGuiInputTextFlags_None = 0, @@ -301,12 +344,13 @@ typedef enum { ImGuiInputTextFlags_DisplayEmptyRefVal = 1 << 14, ImGuiInputTextFlags_NoHorizontalScroll = 1 << 15, ImGuiInputTextFlags_NoUndoRedo = 1 << 16, - ImGuiInputTextFlags_CallbackCompletion = 1 << 17, - ImGuiInputTextFlags_CallbackHistory = 1 << 18, - ImGuiInputTextFlags_CallbackAlways = 1 << 19, - ImGuiInputTextFlags_CallbackCharFilter = 1 << 20, - ImGuiInputTextFlags_CallbackResize = 1 << 21, - ImGuiInputTextFlags_CallbackEdit = 1 << 22, + ImGuiInputTextFlags_ElideLeft = 1 << 17, + ImGuiInputTextFlags_CallbackCompletion = 1 << 18, + ImGuiInputTextFlags_CallbackHistory = 1 << 19, + ImGuiInputTextFlags_CallbackAlways = 1 << 20, + ImGuiInputTextFlags_CallbackCharFilter = 1 << 21, + ImGuiInputTextFlags_CallbackResize = 1 << 22, + ImGuiInputTextFlags_CallbackEdit = 1 << 23, }ImGuiInputTextFlags_; typedef enum { ImGuiTreeNodeFlags_None = 0, @@ -323,10 +367,14 @@ typedef enum { ImGuiTreeNodeFlags_FramePadding = 1 << 10, ImGuiTreeNodeFlags_SpanAvailWidth = 1 << 11, ImGuiTreeNodeFlags_SpanFullWidth = 1 << 12, - ImGuiTreeNodeFlags_SpanTextWidth = 1 << 13, + ImGuiTreeNodeFlags_SpanLabelWidth = 1 << 13, ImGuiTreeNodeFlags_SpanAllColumns = 1 << 14, - ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 15, + ImGuiTreeNodeFlags_LabelSpanAllColumns = 1 << 15, + ImGuiTreeNodeFlags_NavLeftJumpsToParent = 1 << 17, ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog, + ImGuiTreeNodeFlags_DrawLinesNone = 1 << 18, + ImGuiTreeNodeFlags_DrawLinesFull = 1 << 19, + ImGuiTreeNodeFlags_DrawLinesToNodes = 1 << 20, }ImGuiTreeNodeFlags_; typedef enum { ImGuiPopupFlags_None = 0, @@ -458,6 +506,7 @@ typedef enum { ImGuiDataType_Float, ImGuiDataType_Double, ImGuiDataType_Bool, + ImGuiDataType_String, ImGuiDataType_COUNT }ImGuiDataType_; typedef enum { @@ -475,6 +524,7 @@ ImGuiSortDirection_Descending=2, }ImGuiSortDirection; typedef enum { ImGuiKey_None=0, +ImGuiKey_NamedKey_BEGIN=512, ImGuiKey_Tab=512, ImGuiKey_LeftArrow=513, ImGuiKey_RightArrow=514, @@ -594,53 +644,50 @@ ImGuiKey_KeypadEnter=627, ImGuiKey_KeypadEqual=628, ImGuiKey_AppBack=629, ImGuiKey_AppForward=630, -ImGuiKey_GamepadStart=631, -ImGuiKey_GamepadBack=632, -ImGuiKey_GamepadFaceLeft=633, -ImGuiKey_GamepadFaceRight=634, -ImGuiKey_GamepadFaceUp=635, -ImGuiKey_GamepadFaceDown=636, -ImGuiKey_GamepadDpadLeft=637, -ImGuiKey_GamepadDpadRight=638, -ImGuiKey_GamepadDpadUp=639, -ImGuiKey_GamepadDpadDown=640, -ImGuiKey_GamepadL1=641, -ImGuiKey_GamepadR1=642, -ImGuiKey_GamepadL2=643, -ImGuiKey_GamepadR2=644, -ImGuiKey_GamepadL3=645, -ImGuiKey_GamepadR3=646, -ImGuiKey_GamepadLStickLeft=647, -ImGuiKey_GamepadLStickRight=648, -ImGuiKey_GamepadLStickUp=649, -ImGuiKey_GamepadLStickDown=650, -ImGuiKey_GamepadRStickLeft=651, -ImGuiKey_GamepadRStickRight=652, -ImGuiKey_GamepadRStickUp=653, -ImGuiKey_GamepadRStickDown=654, -ImGuiKey_MouseLeft=655, -ImGuiKey_MouseRight=656, -ImGuiKey_MouseMiddle=657, -ImGuiKey_MouseX1=658, -ImGuiKey_MouseX2=659, -ImGuiKey_MouseWheelX=660, -ImGuiKey_MouseWheelY=661, -ImGuiKey_ReservedForModCtrl=662, -ImGuiKey_ReservedForModShift=663, -ImGuiKey_ReservedForModAlt=664, -ImGuiKey_ReservedForModSuper=665, -ImGuiKey_COUNT=666, +ImGuiKey_Oem102=631, +ImGuiKey_GamepadStart=632, +ImGuiKey_GamepadBack=633, +ImGuiKey_GamepadFaceLeft=634, +ImGuiKey_GamepadFaceRight=635, +ImGuiKey_GamepadFaceUp=636, +ImGuiKey_GamepadFaceDown=637, +ImGuiKey_GamepadDpadLeft=638, +ImGuiKey_GamepadDpadRight=639, +ImGuiKey_GamepadDpadUp=640, +ImGuiKey_GamepadDpadDown=641, +ImGuiKey_GamepadL1=642, +ImGuiKey_GamepadR1=643, +ImGuiKey_GamepadL2=644, +ImGuiKey_GamepadR2=645, +ImGuiKey_GamepadL3=646, +ImGuiKey_GamepadR3=647, +ImGuiKey_GamepadLStickLeft=648, +ImGuiKey_GamepadLStickRight=649, +ImGuiKey_GamepadLStickUp=650, +ImGuiKey_GamepadLStickDown=651, +ImGuiKey_GamepadRStickLeft=652, +ImGuiKey_GamepadRStickRight=653, +ImGuiKey_GamepadRStickUp=654, +ImGuiKey_GamepadRStickDown=655, +ImGuiKey_MouseLeft=656, +ImGuiKey_MouseRight=657, +ImGuiKey_MouseMiddle=658, +ImGuiKey_MouseX1=659, +ImGuiKey_MouseX2=660, +ImGuiKey_MouseWheelX=661, +ImGuiKey_MouseWheelY=662, +ImGuiKey_ReservedForModCtrl=663, +ImGuiKey_ReservedForModShift=664, +ImGuiKey_ReservedForModAlt=665, +ImGuiKey_ReservedForModSuper=666, +ImGuiKey_NamedKey_END=667, +ImGuiKey_NamedKey_COUNT=ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN, ImGuiMod_None=0, ImGuiMod_Ctrl=1 << 12, ImGuiMod_Shift=1 << 13, ImGuiMod_Alt=1 << 14, ImGuiMod_Super=1 << 15, ImGuiMod_Mask_=0xF000, -ImGuiKey_NamedKey_BEGIN=512, -ImGuiKey_NamedKey_END=ImGuiKey_COUNT, -ImGuiKey_NamedKey_COUNT=ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN, -ImGuiKey_KeysData_SIZE=ImGuiKey_NamedKey_COUNT, -ImGuiKey_KeysData_OFFSET=ImGuiKey_NamedKey_BEGIN, }ImGuiKey; typedef enum { ImGuiInputFlags_None = 0, @@ -659,15 +706,11 @@ typedef enum { ImGuiConfigFlags_None = 0, ImGuiConfigFlags_NavEnableKeyboard = 1 << 0, ImGuiConfigFlags_NavEnableGamepad = 1 << 1, - ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, - ImGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3, ImGuiConfigFlags_NoMouse = 1 << 4, ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, ImGuiConfigFlags_NoKeyboard = 1 << 6, ImGuiConfigFlags_DockingEnable = 1 << 7, ImGuiConfigFlags_ViewportsEnable = 1 << 10, - ImGuiConfigFlags_DpiEnableScaleViewports= 1 << 14, - ImGuiConfigFlags_DpiEnableScaleFonts = 1 << 15, ImGuiConfigFlags_IsSRGB = 1 << 20, ImGuiConfigFlags_IsTouchScreen = 1 << 21, }ImGuiConfigFlags_; @@ -677,6 +720,7 @@ typedef enum { ImGuiBackendFlags_HasMouseCursors = 1 << 1, ImGuiBackendFlags_HasSetMousePos = 1 << 2, ImGuiBackendFlags_RendererHasVtxOffset = 1 << 3, + ImGuiBackendFlags_RendererHasTextures = 1 << 4, ImGuiBackendFlags_PlatformHasViewports = 1 << 10, ImGuiBackendFlags_HasMouseHoveredViewport=1 << 11, ImGuiBackendFlags_RendererHasViewports = 1 << 12, @@ -715,6 +759,7 @@ typedef enum { ImGuiCol_ResizeGrip, ImGuiCol_ResizeGripHovered, ImGuiCol_ResizeGripActive, + ImGuiCol_InputTextCursor, ImGuiCol_TabHovered, ImGuiCol_Tab, ImGuiCol_TabSelected, @@ -735,8 +780,9 @@ typedef enum { ImGuiCol_TableRowBgAlt, ImGuiCol_TextLink, ImGuiCol_TextSelectedBg, + ImGuiCol_TreeLines, ImGuiCol_DragDropTarget, - ImGuiCol_NavHighlight, + ImGuiCol_NavCursor, ImGuiCol_NavWindowingHighlight, ImGuiCol_NavWindowingDimBg, ImGuiCol_ModalWindowDimBg, @@ -765,12 +811,15 @@ typedef enum { ImGuiStyleVar_ScrollbarRounding, ImGuiStyleVar_GrabMinSize, ImGuiStyleVar_GrabRounding, + ImGuiStyleVar_ImageBorderSize, ImGuiStyleVar_TabRounding, ImGuiStyleVar_TabBorderSize, ImGuiStyleVar_TabBarBorderSize, ImGuiStyleVar_TabBarOverlineSize, ImGuiStyleVar_TableAngledHeadersAngle, ImGuiStyleVar_TableAngledHeadersTextAlign, + ImGuiStyleVar_TreeLinesSize, + ImGuiStyleVar_TreeLinesRounding, ImGuiStyleVar_ButtonTextAlign, ImGuiStyleVar_SelectableTextAlign, ImGuiStyleVar_SeparatorTextBorderSize, @@ -785,6 +834,7 @@ typedef enum { ImGuiButtonFlags_MouseButtonRight = 1 << 1, ImGuiButtonFlags_MouseButtonMiddle = 1 << 2, ImGuiButtonFlags_MouseButtonMask_ = ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle, + ImGuiButtonFlags_EnableNav = 1 << 3, }ImGuiButtonFlags_; typedef enum { ImGuiColorEditFlags_None = 0, @@ -798,9 +848,10 @@ typedef enum { ImGuiColorEditFlags_NoSidePreview = 1 << 8, ImGuiColorEditFlags_NoDragDrop = 1 << 9, ImGuiColorEditFlags_NoBorder = 1 << 10, + ImGuiColorEditFlags_AlphaOpaque = 1 << 11, + ImGuiColorEditFlags_AlphaNoBg = 1 << 12, + ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 13, ImGuiColorEditFlags_AlphaBar = 1 << 16, - ImGuiColorEditFlags_AlphaPreview = 1 << 17, - ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 18, ImGuiColorEditFlags_HDR = 1 << 19, ImGuiColorEditFlags_DisplayRGB = 1 << 20, ImGuiColorEditFlags_DisplayHSV = 1 << 21, @@ -812,6 +863,7 @@ typedef enum { ImGuiColorEditFlags_InputRGB = 1 << 27, ImGuiColorEditFlags_InputHSV = 1 << 28, ImGuiColorEditFlags_DefaultOptions_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_PickerHueBar, + ImGuiColorEditFlags_AlphaMask_ = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaOpaque | ImGuiColorEditFlags_AlphaNoBg | ImGuiColorEditFlags_AlphaPreviewHalf, ImGuiColorEditFlags_DisplayMask_ = ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_DisplayHex, ImGuiColorEditFlags_DataTypeMask_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_Float, ImGuiColorEditFlags_PickerMask_ = ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_PickerHueBar, @@ -819,11 +871,14 @@ typedef enum { }ImGuiColorEditFlags_; typedef enum { ImGuiSliderFlags_None = 0, - ImGuiSliderFlags_AlwaysClamp = 1 << 4, ImGuiSliderFlags_Logarithmic = 1 << 5, ImGuiSliderFlags_NoRoundToFormat = 1 << 6, ImGuiSliderFlags_NoInput = 1 << 7, ImGuiSliderFlags_WrapAround = 1 << 8, + ImGuiSliderFlags_ClampOnInput = 1 << 9, + ImGuiSliderFlags_ClampZeroRange = 1 << 10, + ImGuiSliderFlags_NoSpeedTweaks = 1 << 11, + ImGuiSliderFlags_AlwaysClamp = ImGuiSliderFlags_ClampOnInput | ImGuiSliderFlags_ClampZeroRange, ImGuiSliderFlags_InvalidMask_ = 0x7000000F, }ImGuiSliderFlags_; typedef enum { @@ -842,6 +897,8 @@ typedef enum { ImGuiMouseCursor_ResizeNESW, ImGuiMouseCursor_ResizeNWSE, ImGuiMouseCursor_Hand, + ImGuiMouseCursor_Wait, + ImGuiMouseCursor_Progress, ImGuiMouseCursor_NotAllowed, ImGuiMouseCursor_COUNT }ImGuiMouseCursor_; @@ -952,11 +1009,15 @@ struct ImGuiTableColumnSortSpecs }; struct ImGuiStyle { + float FontSizeBase; + float FontScaleMain; + float FontScaleDpi; float Alpha; float DisabledAlpha; ImVec2 WindowPadding; float WindowRounding; float WindowBorderSize; + float WindowBorderHoverPadding; ImVec2 WindowMinSize; ImVec2 WindowTitleAlign; ImGuiDir WindowMenuButtonPosition; @@ -978,13 +1039,18 @@ struct ImGuiStyle float GrabMinSize; float GrabRounding; float LogSliderDeadzone; + float ImageBorderSize; float TabRounding; float TabBorderSize; - float TabMinWidthForCloseButton; + float TabCloseButtonMinWidthSelected; + float TabCloseButtonMinWidthUnselected; float TabBarBorderSize; float TabBarOverlineSize; float TableAngledHeadersAngle; ImVec2 TableAngledHeadersTextAlign; + ImGuiTreeNodeFlags TreeLinesFlags; + float TreeLinesSize; + float TreeLinesRounding; ImGuiDir ColorButtonPosition; ImVec2 ButtonTextAlign; ImVec2 SelectableTextAlign; @@ -1006,6 +1072,8 @@ struct ImGuiStyle float HoverDelayNormal; ImGuiHoveredFlags HoverFlagsForTooltipMouse; ImGuiHoveredFlags HoverFlagsForTooltipNav; + float _MainScale; + float _NextFrameFontSizeBase; }; struct ImGuiKeyData { @@ -1021,16 +1089,22 @@ struct ImGuiIO ImGuiConfigFlags ConfigFlags; ImGuiBackendFlags BackendFlags; ImVec2 DisplaySize; + ImVec2 DisplayFramebufferScale; float DeltaTime; float IniSavingRate; const char* IniFilename; const char* LogFilename; void* UserData; ImFontAtlas*Fonts; - float FontGlobalScale; - bool FontAllowUserScaling; ImFont* FontDefault; - ImVec2 DisplayFramebufferScale; + bool FontAllowUserScaling; + bool ConfigNavSwapGamepadButtons; + bool ConfigNavMoveSetMousePos; + bool ConfigNavCaptureKeyboard; + bool ConfigNavEscapeClearFocusItem; + bool ConfigNavEscapeClearFocusWindow; + bool ConfigNavCursorVisibleAuto; + bool ConfigNavCursorVisibleAlways; bool ConfigDockingNoSplit; bool ConfigDockingWithShift; bool ConfigDockingAlwaysTabBar; @@ -1039,22 +1113,31 @@ struct ImGuiIO bool ConfigViewportsNoTaskBarIcon; bool ConfigViewportsNoDecoration; bool ConfigViewportsNoDefaultParent; + bool ConfigDpiScaleFonts; + bool ConfigDpiScaleViewports; bool MouseDrawCursor; bool ConfigMacOSXBehaviors; - bool ConfigNavSwapGamepadButtons; bool ConfigInputTrickleEventQueue; bool ConfigInputTextCursorBlink; bool ConfigInputTextEnterKeepActive; bool ConfigDragClickToInputText; bool ConfigWindowsResizeFromEdges; bool ConfigWindowsMoveFromTitleBarOnly; + bool ConfigWindowsCopyContentsWithCtrlC; + bool ConfigScrollbarScrollByPage; float ConfigMemoryCompactTimer; float MouseDoubleClickTime; float MouseDoubleClickMaxDist; float MouseDragThreshold; float KeyRepeatDelay; float KeyRepeatRate; + bool ConfigErrorRecovery; + bool ConfigErrorRecoveryEnableAssert; + bool ConfigErrorRecoveryEnableDebugLog; + bool ConfigErrorRecoveryEnableTooltip; bool ConfigDebugIsDebuggerPresent; + bool ConfigDebugHighlightIdConflicts; + bool ConfigDebugHighlightIdConflictsShowItemPicker; bool ConfigDebugBeginReturnValueOnce; bool ConfigDebugBeginReturnValueLoop; bool ConfigDebugIgnoreFocusLoss; @@ -1064,13 +1147,6 @@ struct ImGuiIO void* BackendPlatformUserData; void* BackendRendererUserData; void* BackendLanguageUserData; - const char* (*GetClipboardTextFn)(void* user_data); - void (*SetClipboardTextFn)(void* user_data, const char* text); - void* ClipboardUserData; - bool (*PlatformOpenInShellFn)(ImGuiContext* ctx, const char* path); - void* PlatformOpenInShellUserData; - void (*PlatformSetImeDataFn)(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); - ImWchar PlatformLocaleDecimalPoint; bool WantCaptureMouse; bool WantCaptureKeyboard; bool WantTextInput; @@ -1096,7 +1172,7 @@ struct ImGuiIO bool KeyAlt; bool KeySuper; ImGuiKeyChord KeyMods; - ImGuiKeyData KeysData[ImGuiKey_KeysData_SIZE]; + ImGuiKeyData KeysData[ImGuiKey_NamedKey_COUNT]; bool WantCaptureMouseUnlessPopupClose; ImVec2 MousePosPrev; ImVec2 MouseClickedPos[5]; @@ -1106,6 +1182,7 @@ struct ImGuiIO ImU16 MouseClickedCount[5]; ImU16 MouseClickedLastCount[5]; bool MouseReleased[5]; + double MouseReleasedTime[5]; bool MouseDownOwned[5]; bool MouseDownOwnedUnlessPopupClose[5]; bool MouseWheelRequestAxisSwap; @@ -1117,8 +1194,6 @@ struct ImGuiIO float PenPressure; bool AppFocusLost; bool AppAcceptingEvents; - ImS8 BackendUsingLegacyKeyArrays; - bool BackendUsingLegacyNavInputArray; ImWchar16 InputQueueSurrogate; ImVector_ImWchar InputQueueCharacters; }; @@ -1212,7 +1287,7 @@ struct ImGuiListClipper int DisplayEnd; int ItemsCount; float ItemsHeight; - float StartPosY; + double StartPosY; double StartSeekOffsetY; void* TempData; }; @@ -1277,16 +1352,19 @@ struct ImGuiSelectionExternalStorage void* UserData; void (*AdapterSetItemSelected)(ImGuiSelectionExternalStorage* self, int idx, bool selected); }; +typedef unsigned short ImDrawIdx; typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); struct ImDrawCmd { ImVec4 ClipRect; - ImTextureID TextureId; + ImTextureRef TexRef; unsigned int VtxOffset; unsigned int IdxOffset; unsigned int ElemCount; ImDrawCallback UserCallback; void* UserCallbackData; + int UserCallbackDataSize; + int UserCallbackDataOffset; }; struct ImDrawVert { @@ -1298,7 +1376,7 @@ typedef struct ImDrawCmdHeader ImDrawCmdHeader; struct ImDrawCmdHeader { ImVec4 ClipRect; - ImTextureID TextureId; + ImTextureRef TexRef; unsigned int VtxOffset; }; typedef struct ImVector_ImDrawCmd {int Size;int Capacity;ImDrawCmd* Data;} ImVector_ImDrawCmd; @@ -1347,7 +1425,9 @@ typedef struct ImVector_ImVec2 {int Size;int Capacity;ImVec2* Data;} ImVector_Im typedef struct ImVector_ImVec4 {int Size;int Capacity;ImVec4* Data;} ImVector_ImVec4; -typedef struct ImVector_ImTextureID {int Size;int Capacity;ImTextureID* Data;} ImVector_ImTextureID; +typedef struct ImVector_ImTextureRef {int Size;int Capacity;ImTextureRef* Data;} ImVector_ImTextureRef; + +typedef struct ImVector_ImU8 {int Size;int Capacity;ImU8* Data;} ImVector_ImU8; struct ImDrawList { @@ -1363,12 +1443,15 @@ struct ImDrawList ImDrawCmdHeader _CmdHeader; ImDrawListSplitter _Splitter; ImVector_ImVec4 _ClipRectStack; - ImVector_ImTextureID _TextureIdStack; + ImVector_ImTextureRef _TextureStack; + ImVector_ImU8 _CallbacksDataBuf; float _FringeScale; const char* _OwnerName; }; typedef struct ImVector_ImDrawListPtr {int Size;int Capacity;ImDrawList** Data;} ImVector_ImDrawListPtr; +typedef struct ImVector_ImTextureDataPtr {int Size;int Capacity;ImTextureData** Data;} ImVector_ImTextureDataPtr; + struct ImDrawData { bool Valid; @@ -1380,38 +1463,83 @@ struct ImDrawData ImVec2 DisplaySize; ImVec2 FramebufferScale; ImGuiViewport* OwnerViewport; + ImVector_ImTextureDataPtr* Textures; +}; +typedef enum { + ImTextureFormat_RGBA32, + ImTextureFormat_Alpha8, +}ImTextureFormat; +typedef enum { + ImTextureStatus_OK, + ImTextureStatus_Destroyed, + ImTextureStatus_WantCreate, + ImTextureStatus_WantUpdates, + ImTextureStatus_WantDestroy, +}ImTextureStatus; +struct ImTextureRect +{ + unsigned short x, y; + unsigned short w, h; +}; +typedef struct ImVector_ImTextureRect {int Size;int Capacity;ImTextureRect* Data;} ImVector_ImTextureRect; + +struct ImTextureData +{ + int UniqueID; + ImTextureStatus Status; + void* BackendUserData; + ImTextureID TexID; + ImTextureFormat Format; + int Width; + int Height; + int BytesPerPixel; + unsigned char* Pixels; + ImTextureRect UsedRect; + ImTextureRect UpdateRect; + ImVector_ImTextureRect Updates; + int UnusedFrames; + unsigned short RefCount; + bool UseColors; + bool WantDestroyNextFrame; }; struct ImFontConfig { + char Name[40]; void* FontData; int FontDataSize; bool FontDataOwnedByAtlas; - int FontNo; - float SizePixels; - int OversampleH; - int OversampleV; + bool MergeMode; bool PixelSnapH; - ImVec2 GlyphExtraSpacing; - ImVec2 GlyphOffset; + bool PixelSnapV; + ImS8 FontNo; + ImS8 OversampleH; + ImS8 OversampleV; + float SizePixels; const ImWchar* GlyphRanges; + const ImWchar* GlyphExcludeRanges; + ImVec2 GlyphOffset; float GlyphMinAdvanceX; float GlyphMaxAdvanceX; - bool MergeMode; - unsigned int FontBuilderFlags; + float GlyphExtraAdvanceX; + unsigned int FontLoaderFlags; float RasterizerMultiply; float RasterizerDensity; ImWchar EllipsisChar; - char Name[40]; + ImFontFlags Flags; ImFont* DstFont; + const ImFontLoader* FontLoader; + void* FontLoaderData; }; struct ImFontGlyph { unsigned int Colored : 1; unsigned int Visible : 1; - unsigned int Codepoint : 30; + unsigned int SourceIdx : 4; + unsigned int Codepoint : 26; float AdvanceX; float X0, Y0, X1, Y1; float U0, V0, U1, V1; + int PackId; }; typedef struct ImVector_ImU32 {int Size;int Capacity;ImU32* Data;} ImVector_ImU32; @@ -1419,15 +1547,12 @@ struct ImFontGlyphRangesBuilder { ImVector_ImU32 UsedChars; }; -typedef struct ImFontAtlasCustomRect ImFontAtlasCustomRect; -struct ImFontAtlasCustomRect +typedef int ImFontAtlasRectId; +struct ImFontAtlasRect { - unsigned short Width, Height; - unsigned short X, Y; - unsigned int GlyphID; - float GlyphAdvanceX; - ImVec2 GlyphOffset; - ImFont* Font; + unsigned short x, y; + unsigned short w, h; + ImVec2 uv0, uv1; }; typedef enum { ImFontAtlasFlags_None = 0, @@ -1437,60 +1562,89 @@ typedef enum { }ImFontAtlasFlags_; typedef struct ImVector_ImFontPtr {int Size;int Capacity;ImFont** Data;} ImVector_ImFontPtr; -typedef struct ImVector_ImFontAtlasCustomRect {int Size;int Capacity;ImFontAtlasCustomRect* Data;} ImVector_ImFontAtlasCustomRect; - typedef struct ImVector_ImFontConfig {int Size;int Capacity;ImFontConfig* Data;} ImVector_ImFontConfig; +typedef struct ImVector_ImDrawListSharedDataPtr {int Size;int Capacity;ImDrawListSharedData** Data;} ImVector_ImDrawListSharedDataPtr; + struct ImFontAtlas { ImFontAtlasFlags Flags; - ImTextureID TexID; - int TexDesiredWidth; + ImTextureFormat TexDesiredFormat; int TexGlyphPadding; - bool Locked; + int TexMinWidth; + int TexMinHeight; + int TexMaxWidth; + int TexMaxHeight; void* UserData; - bool TexReady; + ImTextureRef TexRef; + ImTextureData* TexData; + ImVector_ImTextureDataPtr TexList; + bool Locked; + bool RendererHasTextures; + bool TexIsBuilt; bool TexPixelsUseColors; - unsigned char* TexPixelsAlpha8; - unsigned int* TexPixelsRGBA32; - int TexWidth; - int TexHeight; ImVec2 TexUvScale; ImVec2 TexUvWhitePixel; ImVector_ImFontPtr Fonts; - ImVector_ImFontAtlasCustomRect CustomRects; - ImVector_ImFontConfig ConfigData; - ImVec4 TexUvLines[(63) + 1]; - const ImFontBuilderIO* FontBuilderIO; - unsigned int FontBuilderFlags; - int PackIdMouseCursors; - int PackIdLines; + ImVector_ImFontConfig Sources; + ImVec4 TexUvLines[(32) + 1]; + int TexNextUniqueID; + int FontNextUniqueID; + ImVector_ImDrawListSharedDataPtr DrawListSharedDatas; + ImFontAtlasBuilder* Builder; + const ImFontLoader* FontLoader; + const char* FontLoaderName; + void* FontLoaderData; + unsigned int FontLoaderFlags; + int RefCount; + ImGuiContext* OwnerContext; }; typedef struct ImVector_float {int Size;int Capacity;float* Data;} ImVector_float; +typedef struct ImVector_ImU16 {int Size;int Capacity;ImU16* Data;} ImVector_ImU16; + typedef struct ImVector_ImFontGlyph {int Size;int Capacity;ImFontGlyph* Data;} ImVector_ImFontGlyph; -struct ImFont +struct ImFontBaked { ImVector_float IndexAdvanceX; float FallbackAdvanceX; - float FontSize; - ImVector_ImWchar IndexLookup; + float Size; + float RasterizerDensity; + ImVector_ImU16 IndexLookup; ImVector_ImFontGlyph Glyphs; - const ImFontGlyph* FallbackGlyph; - ImFontAtlas* ContainerAtlas; - const ImFontConfig* ConfigData; - short ConfigDataCount; - ImWchar FallbackChar; - ImWchar EllipsisChar; - short EllipsisCharCount; - float EllipsisWidth; - float EllipsisCharStep; - bool DirtyLookupTables; - float Scale; + int FallbackGlyphIndex; float Ascent, Descent; - int MetricsTotalSurface; - ImU8 Used4kPagesMap[(0xFFFF +1)/4096/8]; + unsigned int MetricsTotalSurface:26; + unsigned int WantDestroy:1; + unsigned int LockLoadingFallback:1; + int LastUsedFrame; + ImGuiID BakedId; + ImFont* ContainerFont; + void* FontLoaderDatas; +}; +typedef enum { + ImFontFlags_None = 0, + ImFontFlags_NoLoadError = 1 << 1, + ImFontFlags_NoLoadGlyphs = 1 << 2, + ImFontFlags_LockBakedSizes = 1 << 3, +}ImFontFlags_; +typedef struct ImVector_ImFontConfigPtr {int Size;int Capacity;ImFontConfig** Data;} ImVector_ImFontConfigPtr; + +struct ImFont +{ + ImFontBaked* LastBaked; + ImFontAtlas* ContainerAtlas; + ImFontFlags Flags; + float CurrentRasterizerDensity; + ImGuiID FontId; + float LegacySize; + ImVector_ImFontConfigPtr Sources; + ImWchar EllipsisChar; + ImWchar FallbackChar; + ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX +1)/8192/8]; + bool EllipsisAutoBake; + ImGuiStorage RemapPairs; }; typedef enum { ImGuiViewportFlags_None = 0, @@ -1515,6 +1669,7 @@ struct ImGuiViewport ImGuiViewportFlags Flags; ImVec2 Pos; ImVec2 Size; + ImVec2 FramebufferScale; ImVec2 WorkPos; ImVec2 WorkSize; float DpiScale; @@ -1535,6 +1690,17 @@ typedef struct ImVector_ImGuiViewportPtr {int Size;int Capacity;ImGuiViewport** struct ImGuiPlatformIO { + const char* (*Platform_GetClipboardTextFn)(ImGuiContext* ctx); + void (*Platform_SetClipboardTextFn)(ImGuiContext* ctx, const char* text); + void* Platform_ClipboardUserData; + bool (*Platform_OpenInShellFn)(ImGuiContext* ctx, const char* path); + void* Platform_OpenInShellUserData; + void (*Platform_SetImeDataFn)(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); + void* Platform_ImeUserData; + ImWchar Platform_LocaleDecimalPoint; + int Renderer_TextureMaxWidth; + int Renderer_TextureMaxHeight; + void* Renderer_RenderState; void (*Platform_CreateWindow)(ImGuiViewport* vp); void (*Platform_DestroyWindow)(ImGuiViewport* vp); void (*Platform_ShowWindow)(ImGuiViewport* vp); @@ -1542,6 +1708,7 @@ struct ImGuiPlatformIO ImVec2 (*Platform_GetWindowPos)(ImGuiViewport* vp); void (*Platform_SetWindowSize)(ImGuiViewport* vp, ImVec2 size); ImVec2 (*Platform_GetWindowSize)(ImGuiViewport* vp); + ImVec2 (*Platform_GetWindowFramebufferScale)(ImGuiViewport* vp); void (*Platform_SetWindowFocus)(ImGuiViewport* vp); bool (*Platform_GetWindowFocus)(ImGuiViewport* vp); bool (*Platform_GetWindowMinimized)(ImGuiViewport* vp); @@ -1552,6 +1719,7 @@ struct ImGuiPlatformIO void (*Platform_SwapBuffers)(ImGuiViewport* vp, void* render_arg); float (*Platform_GetWindowDpiScale)(ImGuiViewport* vp); void (*Platform_OnChangedViewport)(ImGuiViewport* vp); + ImVec4 (*Platform_GetWindowWorkAreaInsets)(ImGuiViewport* vp); int (*Platform_CreateVkSurface)(ImGuiViewport* vp, ImU64 vk_inst, const void* vk_allocators, ImU64* out_vk_surface); void (*Renderer_CreateWindow)(ImGuiViewport* vp); void (*Renderer_DestroyWindow)(ImGuiViewport* vp); @@ -1559,6 +1727,7 @@ struct ImGuiPlatformIO void (*Renderer_RenderWindow)(ImGuiViewport* vp, void* render_arg); void (*Renderer_SwapBuffers)(ImGuiViewport* vp, void* render_arg); ImVector_ImGuiPlatformMonitor Monitors; + ImVector_ImTextureDataPtr Textures; ImVector_ImGuiViewportPtr Viewports; }; struct ImGuiPlatformMonitor @@ -1571,23 +1740,30 @@ struct ImGuiPlatformMonitor struct ImGuiPlatformImeData { bool WantVisible; + bool WantTextInput; ImVec2 InputPos; float InputLineHeight; + ImGuiID ViewportId; }; struct ImBitVector; struct ImRect; +struct ImGuiTextIndex; struct ImDrawDataBuilder; struct ImDrawListSharedData; +struct ImFontAtlasBuilder; +struct ImFontAtlasPostProcessData; +struct ImFontAtlasRectEntry; struct ImGuiBoxSelectState; struct ImGuiColorMod; struct ImGuiContext; struct ImGuiContextHook; -struct ImGuiStyleVarInfo; struct ImGuiDataTypeInfo; +struct ImGuiDeactivatedItemData; struct ImGuiDockContext; struct ImGuiDockRequest; struct ImGuiDockNode; struct ImGuiDockNodeSettings; +struct ImGuiErrorRecoveryState; struct ImGuiGroupData; struct ImGuiInputTextState; struct ImGuiInputTextDeactivateData; @@ -1604,8 +1780,8 @@ struct ImGuiOldColumnData; struct ImGuiOldColumns; struct ImGuiPopupData; struct ImGuiSettingsHandler; -struct ImGuiStackSizes; struct ImGuiStyleMod; +struct ImGuiStyleVarInfo; struct ImGuiTabBar; struct ImGuiTabItem; struct ImGuiTable; @@ -1629,7 +1805,8 @@ typedef int ImGuiDebugLogFlags; typedef int ImGuiFocusRequestFlags; typedef int ImGuiItemStatusFlags; typedef int ImGuiOldColumnFlags; -typedef int ImGuiNavHighlightFlags; +typedef int ImGuiLogFlags; +typedef int ImGuiNavRenderCursorFlags; typedef int ImGuiNavMoveFlags; typedef int ImGuiNextItemDataFlags; typedef int ImGuiNextWindowDataFlags; @@ -1639,54 +1816,20 @@ typedef int ImGuiTextFlags; typedef int ImGuiTooltipFlags; typedef int ImGuiTypingSelectFlags; typedef int ImGuiWindowRefreshFlags; -typedef void (*ImGuiErrorLogCallback)(void* user_data, const char* fmt, ...); +typedef ImS16 ImGuiTableColumnIdx; +typedef ImU16 ImGuiTableDrawChannelIdx; extern ImGuiContext* GImGui; -typedef struct StbUndoRecord StbUndoRecord; -struct StbUndoRecord -{ - int where; - int insert_length; - int delete_length; - int char_storage; -}; -typedef struct StbUndoState StbUndoState; -struct StbUndoState -{ - StbUndoRecord undo_rec [99]; - ImWchar undo_char[999]; - short undo_point, redo_point; - int undo_char_point, redo_char_point; -}; -typedef struct STB_TexteditState STB_TexteditState; -struct STB_TexteditState -{ - int cursor; - int select_start; - int select_end; - unsigned char insert_mode; - int row_count_per_page; - unsigned char cursor_at_end_of_line; - unsigned char initialized; - unsigned char has_preferred_x; - unsigned char single_line; - unsigned char padding1, padding2, padding3; - float preferred_x; - StbUndoState undostate; -}; -typedef struct StbTexteditRow StbTexteditRow; -struct StbTexteditRow -{ - float x0,x1; - float baseline_y_delta; - float ymin,ymax; - int num_chars; -}; typedef FILE* ImFileHandle; typedef struct ImVec1 ImVec1; struct ImVec1 { float x; }; +typedef struct ImVec2i ImVec2i; +struct ImVec2i +{ + int x, y; +}; typedef struct ImVec2ih ImVec2ih; struct ImVec2ih { @@ -1703,7 +1846,6 @@ struct ImBitVector ImVector_ImU32 Storage; }; typedef int ImPoolIdx; -typedef struct ImGuiTextIndex ImGuiTextIndex; typedef struct ImVector_int {int Size;int Capacity;int* Data;} ImVector_int; struct ImGuiTextIndex @@ -1714,29 +1856,50 @@ struct ImGuiTextIndex struct ImDrawListSharedData { ImVec2 TexUvWhitePixel; + const ImVec4* TexUvLines; + ImFontAtlas* FontAtlas; ImFont* Font; float FontSize; float FontScale; float CurveTessellationTol; float CircleSegmentMaxError; - ImVec4 ClipRectFullscreen; + float InitialFringeScale; ImDrawListFlags InitialFlags; + ImVec4 ClipRectFullscreen; ImVector_ImVec2 TempBuffer; + ImVector_ImDrawListPtr DrawLists; + ImGuiContext* Context; ImVec2 ArcFastVtx[48]; float ArcFastRadiusCutoff; ImU8 CircleSegmentCounts[64]; - const ImVec4* TexUvLines; }; struct ImDrawDataBuilder { ImVector_ImDrawListPtr* Layers[2]; ImVector_ImDrawListPtr LayerData1; }; +typedef struct ImFontStackData ImFontStackData; +struct ImFontStackData +{ + ImFont* Font; + float FontSizeBeforeScaling; + float FontSizeAfterScaling; +}; struct ImGuiStyleVarInfo { - ImU32 Count : 8; - ImGuiDataType DataType : 8; - ImU32 Offset : 16; + ImU32 Count : 8; + ImGuiDataType DataType : 8; + ImU32 Offset : 16; +}; +struct ImGuiColorMod +{ + ImGuiCol Col; + ImVec4 BackupValue; +}; +struct ImGuiStyleMod +{ + ImGuiStyleVar VarIdx; + union { int BackupInt[2]; float BackupFloat[2]; }; }; typedef struct ImGuiDataTypeStorage ImGuiDataTypeStorage; struct ImGuiDataTypeStorage @@ -1751,8 +1914,7 @@ struct ImGuiDataTypeInfo const char* ScanFmt; }; typedef enum { - ImGuiDataType_String = ImGuiDataType_COUNT + 1, - ImGuiDataType_Pointer, + ImGuiDataType_Pointer = ImGuiDataType_COUNT, ImGuiDataType_ID, }ImGuiDataTypePrivate_; typedef enum { @@ -1761,6 +1923,9 @@ typedef enum { ImGuiItemFlags_MixedValue = 1 << 12, ImGuiItemFlags_NoWindowHoverableCheck = 1 << 13, ImGuiItemFlags_AllowOverlap = 1 << 14, + ImGuiItemFlags_NoNavDisableMouseHover = 1 << 15, + ImGuiItemFlags_NoMarkEdited = 1 << 16, + ImGuiItemFlags_NoFocus = 1 << 17, ImGuiItemFlags_Inputable = 1 << 20, ImGuiItemFlags_HasSelectionUserData = 1 << 21, ImGuiItemFlags_IsMultiSelect = 1 << 22, @@ -1787,9 +1952,8 @@ typedef enum { }ImGuiHoveredFlagsPrivate_; typedef enum { ImGuiInputTextFlags_Multiline = 1 << 26, - ImGuiInputTextFlags_NoMarkEdited = 1 << 27, - ImGuiInputTextFlags_MergedItem = 1 << 28, - ImGuiInputTextFlags_LocalizeDecimalPoint= 1 << 29, + ImGuiInputTextFlags_MergedItem = 1 << 27, + ImGuiInputTextFlags_LocalizeDecimalPoint= 1 << 28, }ImGuiInputTextFlagsPrivate_; typedef enum { ImGuiButtonFlags_PressedOnClick = 1 << 4, @@ -1798,17 +1962,16 @@ typedef enum { ImGuiButtonFlags_PressedOnRelease = 1 << 7, ImGuiButtonFlags_PressedOnDoubleClick = 1 << 8, ImGuiButtonFlags_PressedOnDragDropHold = 1 << 9, - ImGuiButtonFlags_Repeat = 1 << 10, ImGuiButtonFlags_FlattenChildren = 1 << 11, ImGuiButtonFlags_AllowOverlap = 1 << 12, - ImGuiButtonFlags_DontClosePopups = 1 << 13, ImGuiButtonFlags_AlignTextBaseLine = 1 << 15, - ImGuiButtonFlags_NoKeyModifiers = 1 << 16, + ImGuiButtonFlags_NoKeyModsAllowed = 1 << 16, ImGuiButtonFlags_NoHoldingActiveId = 1 << 17, ImGuiButtonFlags_NoNavFocus = 1 << 18, ImGuiButtonFlags_NoHoveredOnFocus = 1 << 19, ImGuiButtonFlags_NoSetKeyOwner = 1 << 20, ImGuiButtonFlags_NoTestKeyOwner = 1 << 21, + ImGuiButtonFlags_NoFocus = 1 << 22, ImGuiButtonFlags_PressedOnMask_ = ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_PressedOnDragDropHold, ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease, }ImGuiButtonFlagsPrivate_; @@ -1830,8 +1993,11 @@ typedef enum { ImGuiSelectableFlags_NoSetKeyOwner = 1 << 27, }ImGuiSelectableFlagsPrivate_; typedef enum { + ImGuiTreeNodeFlags_NoNavFocus = 1 << 27, ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 28, ImGuiTreeNodeFlags_UpsideDownArrow = 1 << 29, + ImGuiTreeNodeFlags_OpenOnMask_ = ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_OpenOnArrow, + ImGuiTreeNodeFlags_DrawLinesMask_ = ImGuiTreeNodeFlags_DrawLinesNone | ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes, }ImGuiTreeNodeFlagsPrivate_; typedef enum { ImGuiSeparatorFlags_None = 0, @@ -1857,12 +2023,13 @@ typedef enum { ImGuiLayoutType_Vertical = 1 }ImGuiLayoutType_; typedef enum { - ImGuiLogType_None = 0, - ImGuiLogType_TTY, - ImGuiLogType_File, - ImGuiLogType_Buffer, - ImGuiLogType_Clipboard, -}ImGuiLogType; + ImGuiLogFlags_None = 0, + ImGuiLogFlags_OutputTTY = 1 << 0, + ImGuiLogFlags_OutputFile = 1 << 1, + ImGuiLogFlags_OutputBuffer = 1 << 2, + ImGuiLogFlags_OutputClipboard = 1 << 3, + ImGuiLogFlags_OutputMask_ = ImGuiLogFlags_OutputTTY | ImGuiLogFlags_OutputFile | ImGuiLogFlags_OutputBuffer | ImGuiLogFlags_OutputClipboard, +}ImGuiLogFlags_; typedef enum { ImGuiAxis_None = -1, ImGuiAxis_X = 0, @@ -1872,16 +2039,6 @@ typedef enum { ImGuiPlotType_Lines, ImGuiPlotType_Histogram, }ImGuiPlotType; -struct ImGuiColorMod -{ - ImGuiCol Col; - ImVec4 BackupValue; -}; -struct ImGuiStyleMod -{ - ImGuiStyleVar VarIdx; - union { int BackupInt[2]; float BackupFloat[2]; }; -}; typedef struct ImGuiComboPreviewData ImGuiComboPreviewData; struct ImGuiComboPreviewData { @@ -1903,7 +2060,7 @@ struct ImGuiGroupData ImVec2 BackupCurrLineSize; float BackupCurrLineTextBaseOffset; ImGuiID BackupActiveIdIsAlive; - bool BackupActiveIdPreviousFrameIsAlive; + bool BackupDeactivatedIdIsAlive; bool BackupHoveredIdIsAlive; bool BackupIsSameLine; bool EmitItem; @@ -1924,25 +2081,26 @@ struct ImGuiInputTextDeactivatedState { ImGuiID ID; ImVector_char TextA; -}; +}; struct STB_TexteditState; +typedef STB_TexteditState ImStbTexteditState; struct ImGuiInputTextState { ImGuiContext* Ctx; + ImStbTexteditState* Stb; + ImGuiInputTextFlags Flags; ImGuiID ID; - int CurLenW, CurLenA; - ImVector_ImWchar TextW; + int TextLen; + const char* TextSrc; ImVector_char TextA; - ImVector_char InitialTextA; - bool TextAIsValid; - int BufCapacityA; - float ScrollX; - STB_TexteditState Stb; + ImVector_char TextToRevertTo; + ImVector_char CallbackTextBackup; + int BufCapacity; + ImVec2 Scroll; float CursorAnim; bool CursorFollow; bool SelectedAllMouseLock; bool Edited; - ImGuiInputTextFlags Flags; - bool ReloadUserBuf; + bool WantReloadUserBuf; int ReloadSelectionStart; int ReloadSelectionEnd; }; @@ -1962,15 +2120,16 @@ typedef enum { ImGuiNextWindowDataFlags_HasFocus = 1 << 5, ImGuiNextWindowDataFlags_HasBgAlpha = 1 << 6, ImGuiNextWindowDataFlags_HasScroll = 1 << 7, - ImGuiNextWindowDataFlags_HasChildFlags = 1 << 8, - ImGuiNextWindowDataFlags_HasRefreshPolicy = 1 << 9, - ImGuiNextWindowDataFlags_HasViewport = 1 << 10, - ImGuiNextWindowDataFlags_HasDock = 1 << 11, - ImGuiNextWindowDataFlags_HasWindowClass = 1 << 12, + ImGuiNextWindowDataFlags_HasWindowFlags = 1 << 8, + ImGuiNextWindowDataFlags_HasChildFlags = 1 << 9, + ImGuiNextWindowDataFlags_HasRefreshPolicy = 1 << 10, + ImGuiNextWindowDataFlags_HasViewport = 1 << 11, + ImGuiNextWindowDataFlags_HasDock = 1 << 12, + ImGuiNextWindowDataFlags_HasWindowClass = 1 << 13, }ImGuiNextWindowDataFlags_; struct ImGuiNextWindowData { - ImGuiNextWindowDataFlags Flags; + ImGuiNextWindowDataFlags HasFlags; ImGuiCond PosCond; ImGuiCond SizeCond; ImGuiCond CollapsedCond; @@ -1980,6 +2139,7 @@ struct ImGuiNextWindowData ImVec2 SizeVal; ImVec2 ContentSizeVal; ImVec2 ScrollVal; + ImGuiWindowFlags WindowFlags; ImGuiChildFlags ChildFlags; bool PosUndock; bool CollapsedVal; @@ -2003,7 +2163,7 @@ typedef enum { }ImGuiNextItemDataFlags_; struct ImGuiNextItemData { - ImGuiNextItemDataFlags Flags; + ImGuiNextItemDataFlags HasFlags; ImGuiItemFlags ItemFlags; ImGuiID FocusScopeId; ImGuiSelectionUserData SelectionUserData; @@ -2018,7 +2178,7 @@ struct ImGuiNextItemData struct ImGuiLastItemData { ImGuiID ID; - ImGuiItemFlags InFlags; + ImGuiItemFlags ItemFlags; ImGuiItemStatusFlags StatusFlags; ImRect Rect; ImRect NavRect; @@ -2030,12 +2190,17 @@ struct ImGuiTreeNodeStackData { ImGuiID ID; ImGuiTreeNodeFlags TreeFlags; - ImGuiItemFlags InFlags; + ImGuiItemFlags ItemFlags; ImRect NavRect; + float DrawLinesX1; + float DrawLinesToNodesY2; + ImGuiTableColumnIdx DrawLinesTableColumn; }; -struct ImGuiStackSizes +struct ImGuiErrorRecoveryState { + short SizeOfWindowStack; short SizeOfIDStack; + short SizeOfTreeStack; short SizeOfColorStack; short SizeOfStyleVarStack; short SizeOfFontStack; @@ -2050,8 +2215,9 @@ struct ImGuiWindowStackData { ImGuiWindow* Window; ImGuiLastItemData ParentLastItemDataBackup; - ImGuiStackSizes StackSizesOnBegin; + ImGuiErrorRecoveryState StackSizesInBegin; bool DisabledOverrideReenable; + float DisabledOverrideReenableAlphaBackup; }; typedef struct ImGuiShrinkWidthItem ImGuiShrinkWidthItem; struct ImGuiShrinkWidthItem @@ -2066,6 +2232,13 @@ struct ImGuiPtrOrIndex void* Ptr; int Index; }; +struct ImGuiDeactivatedItemData +{ + ImGuiID ID; + int ElapseFrame; + bool HasBeenEditedBefore; + bool IsAlive; +}; typedef enum { ImGuiPopupPositionPolicy_Default, ImGuiPopupPositionPolicy_ComboBox, @@ -2244,11 +2417,11 @@ typedef enum { ImGuiScrollFlags_MaskY_ = ImGuiScrollFlags_KeepVisibleEdgeY | ImGuiScrollFlags_KeepVisibleCenterY | ImGuiScrollFlags_AlwaysCenterY, }ImGuiScrollFlags_; typedef enum { - ImGuiNavHighlightFlags_None = 0, - ImGuiNavHighlightFlags_Compact = 1 << 1, - ImGuiNavHighlightFlags_AlwaysDraw = 1 << 2, - ImGuiNavHighlightFlags_NoRounding = 1 << 3, -}ImGuiNavHighlightFlags_; + ImGuiNavRenderCursorFlags_None = 0, + ImGuiNavRenderCursorFlags_Compact = 1 << 1, + ImGuiNavRenderCursorFlags_AlwaysDraw = 1 << 2, + ImGuiNavRenderCursorFlags_NoRounding = 1 << 3, +}ImGuiNavRenderCursorFlags_; typedef enum { ImGuiNavMoveFlags_None = 0, ImGuiNavMoveFlags_LoopX = 1 << 0, @@ -2266,7 +2439,7 @@ typedef enum { ImGuiNavMoveFlags_IsPageMove = 1 << 11, ImGuiNavMoveFlags_Activate = 1 << 12, ImGuiNavMoveFlags_NoSelect = 1 << 13, - ImGuiNavMoveFlags_NoSetNavHighlight = 1 << 14, + ImGuiNavMoveFlags_NoSetNavCursorVisible = 1 << 14, ImGuiNavMoveFlags_NoClearActiveId = 1 << 15, }ImGuiNavMoveFlags_; typedef enum { @@ -2280,7 +2453,7 @@ struct ImGuiNavItemData ImGuiID ID; ImGuiID FocusScopeId; ImRect RectRel; - ImGuiItemFlags InFlags; + ImGuiItemFlags ItemFlags; float DistBox; float DistCenter; float DistAxial; @@ -2414,8 +2587,8 @@ typedef enum { ImGuiDockNodeFlags_NoDockingOverEmpty = 1 << 22, ImGuiDockNodeFlags_NoDocking = ImGuiDockNodeFlags_NoDockingOverMe | ImGuiDockNodeFlags_NoDockingOverOther | ImGuiDockNodeFlags_NoDockingOverEmpty | ImGuiDockNodeFlags_NoDockingSplit | ImGuiDockNodeFlags_NoDockingSplitOther, ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0, - ImGuiDockNodeFlags_NoResizeFlagsMask_ = ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_NoResizeX | ImGuiDockNodeFlags_NoResizeY, - ImGuiDockNodeFlags_LocalFlagsTransferMask_ = ImGuiDockNodeFlags_NoDockingSplit | ImGuiDockNodeFlags_NoResizeFlagsMask_ | ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton, + ImGuiDockNodeFlags_NoResizeFlagsMask_ = (int)ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_NoResizeX | ImGuiDockNodeFlags_NoResizeY, + ImGuiDockNodeFlags_LocalFlagsTransferMask_ = (int)ImGuiDockNodeFlags_NoDockingSplit | ImGuiDockNodeFlags_NoResizeFlagsMask_ | (int)ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton, ImGuiDockNodeFlags_SavedFlagsMask_ = ImGuiDockNodeFlags_NoResizeFlagsMask_ | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton, }ImGuiDockNodeFlagsPrivate_; typedef enum { @@ -2512,6 +2685,7 @@ struct ImGuiViewportP int LastFocusedStampCount; ImGuiID LastNameHash; ImVec2 LastPos; + ImVec2 LastSize; float Alpha; float LastAlpha; bool LastFocusedHadNavWindow; @@ -2523,10 +2697,10 @@ struct ImGuiViewportP ImVec2 LastPlatformPos; ImVec2 LastPlatformSize; ImVec2 LastRendererSize; - ImVec2 WorkOffsetMin; - ImVec2 WorkOffsetMax; - ImVec2 BuildWorkOffsetMin; - ImVec2 BuildWorkOffsetMax; + ImVec2 WorkInsetMin; + ImVec2 WorkInsetMax; + ImVec2 BuildWorkInsetMin; + ImVec2 BuildWorkInsetMax; }; struct ImGuiWindowSettings { @@ -2564,30 +2738,34 @@ ImGuiLocKey_TableResetOrder=4, ImGuiLocKey_WindowingMainMenuBar=5, ImGuiLocKey_WindowingPopup=6, ImGuiLocKey_WindowingUntitled=7, -ImGuiLocKey_CopyLink=8, -ImGuiLocKey_DockingHideTabBar=9, -ImGuiLocKey_DockingHoldShiftToDock=10, -ImGuiLocKey_DockingDragToUndockOrMoveNode=11, -ImGuiLocKey_COUNT=12, +ImGuiLocKey_OpenLink_s=8, +ImGuiLocKey_CopyLink=9, +ImGuiLocKey_DockingHideTabBar=10, +ImGuiLocKey_DockingHoldShiftToDock=11, +ImGuiLocKey_DockingDragToUndockOrMoveNode=12, +ImGuiLocKey_COUNT=13, }ImGuiLocKey; struct ImGuiLocEntry { ImGuiLocKey Key; const char* Text; }; +typedef void (*ImGuiErrorCallback)(ImGuiContext* ctx, void* user_data, const char* msg); typedef enum { ImGuiDebugLogFlags_None = 0, - ImGuiDebugLogFlags_EventActiveId = 1 << 0, - ImGuiDebugLogFlags_EventFocus = 1 << 1, - ImGuiDebugLogFlags_EventPopup = 1 << 2, - ImGuiDebugLogFlags_EventNav = 1 << 3, - ImGuiDebugLogFlags_EventClipper = 1 << 4, - ImGuiDebugLogFlags_EventSelection = 1 << 5, - ImGuiDebugLogFlags_EventIO = 1 << 6, - ImGuiDebugLogFlags_EventInputRouting = 1 << 7, - ImGuiDebugLogFlags_EventDocking = 1 << 8, - ImGuiDebugLogFlags_EventViewport = 1 << 9, - ImGuiDebugLogFlags_EventMask_ = ImGuiDebugLogFlags_EventActiveId | ImGuiDebugLogFlags_EventFocus | ImGuiDebugLogFlags_EventPopup | ImGuiDebugLogFlags_EventNav | ImGuiDebugLogFlags_EventClipper | ImGuiDebugLogFlags_EventSelection | ImGuiDebugLogFlags_EventIO | ImGuiDebugLogFlags_EventInputRouting | ImGuiDebugLogFlags_EventDocking | ImGuiDebugLogFlags_EventViewport, + ImGuiDebugLogFlags_EventError = 1 << 0, + ImGuiDebugLogFlags_EventActiveId = 1 << 1, + ImGuiDebugLogFlags_EventFocus = 1 << 2, + ImGuiDebugLogFlags_EventPopup = 1 << 3, + ImGuiDebugLogFlags_EventNav = 1 << 4, + ImGuiDebugLogFlags_EventClipper = 1 << 5, + ImGuiDebugLogFlags_EventSelection = 1 << 6, + ImGuiDebugLogFlags_EventIO = 1 << 7, + ImGuiDebugLogFlags_EventFont = 1 << 8, + ImGuiDebugLogFlags_EventInputRouting = 1 << 9, + ImGuiDebugLogFlags_EventDocking = 1 << 10, + ImGuiDebugLogFlags_EventViewport = 1 << 11, + ImGuiDebugLogFlags_EventMask_ = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_EventActiveId | ImGuiDebugLogFlags_EventFocus | ImGuiDebugLogFlags_EventPopup | ImGuiDebugLogFlags_EventNav | ImGuiDebugLogFlags_EventClipper | ImGuiDebugLogFlags_EventSelection | ImGuiDebugLogFlags_EventIO | ImGuiDebugLogFlags_EventFont | ImGuiDebugLogFlags_EventInputRouting | ImGuiDebugLogFlags_EventDocking | ImGuiDebugLogFlags_EventViewport, ImGuiDebugLogFlags_OutputToTTY = 1 << 20, ImGuiDebugLogFlags_OutputToTestEngine = 1 << 21, }ImGuiDebugLogFlags_; @@ -2616,12 +2794,13 @@ struct ImGuiMetricsConfig bool ShowDrawCmdMesh; bool ShowDrawCmdBoundingBoxes; bool ShowTextEncodingViewer; - bool ShowAtlasTintedWithTextColor; + bool ShowTextureUsedRect; bool ShowDockingNodes; int ShowWindowsRectsType; int ShowTablesRectsType; int HighlightMonitorIdx; ImGuiID HighlightViewportID; + bool ShowFontPreview; }; typedef struct ImGuiStackLevelInfo ImGuiStackLevelInfo; struct ImGuiStackLevelInfo @@ -2643,6 +2822,7 @@ struct ImGuiIDStackTool ImVector_ImGuiStackLevelInfo Results; bool CopyToClipboardOnCtrlC; float CopyToClipboardLastTime; + ImGuiTextBuffer ResultPathBuf; }; typedef void (*ImGuiContextHookCallback)(ImGuiContext* ctx, ImGuiContextHook* hook); typedef enum { ImGuiContextHookType_NewFramePre, ImGuiContextHookType_NewFramePost, ImGuiContextHookType_EndFramePre, ImGuiContextHookType_EndFramePost, ImGuiContextHookType_RenderPre, ImGuiContextHookType_RenderPost, ImGuiContextHookType_Shutdown, ImGuiContextHookType_PendingRemoval_ }ImGuiContextHookType; @@ -2654,6 +2834,8 @@ struct ImGuiContextHook ImGuiContextHookCallback Callback; void* UserData; }; +typedef struct ImVector_ImFontAtlasPtr {int Size;int Capacity;ImFontAtlas** Data;} ImVector_ImFontAtlasPtr; + typedef struct ImVector_ImGuiInputEvent {int Size;int Capacity;ImGuiInputEvent* Data;} ImVector_ImGuiInputEvent; typedef struct ImVector_ImGuiWindowStackData {int Size;int Capacity;ImGuiWindowStackData* Data;} ImVector_ImGuiWindowStackData; @@ -2662,6 +2844,8 @@ typedef struct ImVector_ImGuiColorMod {int Size;int Capacity;ImGuiColorMod* Data typedef struct ImVector_ImGuiStyleMod {int Size;int Capacity;ImGuiStyleMod* Data;} ImVector_ImGuiStyleMod; +typedef struct ImVector_ImFontStackData {int Size;int Capacity;ImFontStackData* Data;} ImVector_ImFontStackData; + typedef struct ImVector_ImGuiFocusScopeData {int Size;int Capacity;ImGuiFocusScopeData* Data;} ImVector_ImGuiFocusScopeData; typedef struct ImVector_ImGuiItemFlags {int Size;int Capacity;ImGuiItemFlags* Data;} ImVector_ImGuiItemFlags; @@ -2711,16 +2895,18 @@ typedef struct ImVector_ImGuiContextHook {int Size;int Capacity;ImGuiContextHook struct ImGuiContext { bool Initialized; - bool FontAtlasOwnedByContext; ImGuiIO IO; ImGuiPlatformIO PlatformIO; ImGuiStyle Style; ImGuiConfigFlags ConfigFlagsCurrFrame; ImGuiConfigFlags ConfigFlagsLastFrame; + ImVector_ImFontAtlasPtr FontAtlases; ImFont* Font; + ImFontBaked* FontBaked; float FontSize; - float FontBaseSize; - float FontScale; + float FontSizeBase; + float FontBakedScale; + float FontRasterizerDensity; float CurrentDpiScale; ImDrawListSharedData DrawListSharedData; double Time; @@ -2728,9 +2914,9 @@ struct ImGuiContext int FrameCountEnded; int FrameCountPlatformEnded; int FrameCountRendered; + ImGuiID WithinEndChildID; bool WithinFrameScope; bool WithinFrameScopeWithImplicitWindow; - bool WithinEndChild; bool GcCompactAll; bool TestEngineHookItems; void* TestEngine; @@ -2745,7 +2931,7 @@ struct ImGuiContext ImVector_ImGuiWindowStackData CurrentWindowStack; ImGuiStorage WindowsById; int WindowsActiveCount; - ImVec2 WindowsHoverPadding; + float WindowsBorderHoverPadding; ImGuiID DebugBreakInWindow; ImGuiWindow* CurrentWindow; ImGuiWindow* HoveredWindow; @@ -2759,9 +2945,11 @@ struct ImGuiContext float WheelingWindowReleaseTimer; ImVec2 WheelingWindowWheelRemainder; ImVec2 WheelingAxisAvg; + ImGuiID DebugDrawIdConflicts; ImGuiID DebugHookIdInfo; ImGuiID HoveredId; ImGuiID HoveredIdPreviousFrame; + int HoveredIdPreviousFrameItemCount; float HoveredIdTimer; float HoveredIdNotActiveTimer; bool HoveredIdAllowOverlap; @@ -2782,9 +2970,8 @@ struct ImGuiContext ImGuiWindow* ActiveIdWindow; ImGuiInputSource ActiveIdSource; ImGuiID ActiveIdPreviousFrame; - bool ActiveIdPreviousFrameIsAlive; - bool ActiveIdPreviousFrameHasBeenEditedBefore; - ImGuiWindow* ActiveIdPreviousFrameWindow; + ImGuiDeactivatedItemData DeactivatedItemData; + ImGuiDataTypeStorage ActiveIdValueOnActivation; ImGuiID LastActiveId; float LastActiveIdTimer; double LastKeyModsChangeTime; @@ -2806,7 +2993,7 @@ struct ImGuiContext ImGuiCol DebugFlashStyleColorIdx; ImVector_ImGuiColorMod ColorStack; ImVector_ImGuiStyleMod StyleVarStack; - ImVector_ImFontPtr FontStack; + ImVector_ImFontStackData FontStack; ImVector_ImGuiFocusScopeData FocusScopeStack; ImVector_ImGuiItemFlags ItemFlagsStack; ImVector_ImGuiGroupData GroupStack; @@ -2823,8 +3010,12 @@ struct ImGuiContext int ViewportCreatedCount; int PlatformWindowsCreatedCount; int ViewportFocusedStampCount; - ImGuiWindow* NavWindow; + bool NavCursorVisible; + bool NavHighlightItemUnderNav; + bool NavMousePosDirty; + bool NavIdIsAlive; ImGuiID NavId; + ImGuiWindow* NavWindow; ImGuiID NavFocusScopeId; ImGuiNavLayer NavLayer; ImGuiID NavActivateId; @@ -2838,10 +3029,7 @@ struct ImGuiContext ImGuiActivateFlags NavNextActivateFlags; ImGuiInputSource NavInputSource; ImGuiSelectionUserData NavLastValidSelectionUserData; - bool NavIdIsAlive; - bool NavMousePosDirty; - bool NavDisableHighlight; - bool NavDisableMouseHover; + ImS8 NavCursorHideFrames; bool NavAnyRequest; bool NavInitRequest; bool NavInitRequestFromMove; @@ -2870,6 +3058,7 @@ struct ImGuiContext ImGuiKeyChord NavJustMovedToKeyMods; bool NavJustMovedToIsTabbing; bool NavJustMovedToHasSelectionData; + bool ConfigNavWindowingWithGamepad; ImGuiKeyChord ConfigNavWindowingKeyNext; ImGuiKeyChord ConfigNavWindowingKeyPrev; ImGuiWindow* NavWindowingTarget; @@ -2877,6 +3066,7 @@ struct ImGuiContext ImGuiWindow* NavWindowingListWindow; float NavWindowingTimer; float NavWindowingHighlightAlpha; + ImGuiInputSource NavWindowingInputSource; bool NavWindowingToggleLayer; ImGuiKey NavWindowingToggleKey; ImVec2 NavWindowingAccumDeltaPos; @@ -2929,7 +3119,8 @@ struct ImGuiContext ImVec2 MouseLastValidPos; ImGuiInputTextState InputTextState; ImGuiInputTextDeactivatedState InputTextDeactivatedState; - ImFont InputTextPasswordFont; + ImFontBaked InputTextPasswordFontBackupBaked; + ImFontFlags InputTextPasswordFontBackupFlags; ImGuiID TempInputId; ImGuiDataTypeStorage DataTypeZeroValue; int BeginMenuDepth; @@ -2954,14 +3145,14 @@ struct ImGuiContext float DragSpeedDefaultRatio; float DisabledAlphaBackup; short DisabledStackSize; - short LockMarkEdited; short TooltipOverrideCount; + ImGuiWindow* TooltipPreviousWindow; ImVector_char ClipboardHandlerData; ImVector_ImGuiID MenusIdSubmittedThisFrame; ImGuiTypingSelectState TypingSelectState; ImGuiPlatformImeData PlatformImeData; ImGuiPlatformImeData PlatformImeDataPrev; - ImGuiID PlatformImeViewport; + ImVector_ImTextureDataPtr UserTextures; ImGuiDockContext DockContext; void (*DockNodeWindowMenuHandler)(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar); bool SettingsLoaded; @@ -2974,7 +3165,8 @@ struct ImGuiContext ImGuiID HookIdNext; const char* LocalizationTable[ImGuiLocKey_COUNT]; bool LogEnabled; - ImGuiLogType LogType; + ImGuiLogFlags LogFlags; + ImGuiWindow* LogWindow; ImFileHandle LogFile; ImGuiTextBuffer LogBuffer; const char* LogNextPrefix; @@ -2984,9 +3176,18 @@ struct ImGuiContext int LogDepthRef; int LogDepthToExpand; int LogDepthToExpandDefault; + ImGuiErrorCallback ErrorCallback; + void* ErrorCallbackUserData; + ImVec2 ErrorTooltipLockedPos; + bool ErrorFirst; + int ErrorCountCurrentFrame; + ImGuiErrorRecoveryState StackSizesInNewFrame; + ImGuiErrorRecoveryState*StackSizesInBeginForCurrentWindow; + int DebugDrawIdConflictsCount; ImGuiDebugLogFlags DebugLogFlags; ImGuiTextBuffer DebugLogBuf; ImGuiTextIndex DebugLogIndex; + int DebugLogSkippedErrors; ImGuiDebugLogFlags DebugLogAutoDisableFlags; ImU8 DebugLogAutoDisableFrames; ImU8 DebugLocateFrames; @@ -3040,6 +3241,7 @@ struct ImGuiWindowTempData ImGuiMenuColumns MenuColumns; int TreeDepth; ImU32 TreeHasStackDataDepthMask; + ImU32 TreeRecordsClippedNodesY2Mask; ImVector_ImGuiWindowPtr ChildWindows; ImGuiStorage* StateStorage; ImGuiOldColumns* CurrentColumns; @@ -3047,6 +3249,10 @@ struct ImGuiWindowTempData ImGuiLayoutType LayoutType; ImGuiLayoutType ParentLayoutType; ImU32 ModalDimBgColor; + ImGuiItemStatusFlags WindowItemStatusFlags; + ImGuiItemStatusFlags ChildItemStatusFlags; + ImGuiItemStatusFlags DockTabItemStatusFlags; + ImRect DockTabItemRect; float ItemWidth; float TextWrapPos; ImVector_float ItemWidthStack; @@ -3091,6 +3297,8 @@ struct ImGuiWindow ImVec2 ScrollTargetEdgeSnapDist; ImVec2 ScrollbarSizes; bool ScrollbarX, ScrollbarY; + bool ScrollbarXStabilizeEnabled; + ImU8 ScrollbarXStabilizeToggledHistory; bool ViewportOwned; bool Active; bool WasActive; @@ -3142,7 +3350,8 @@ struct ImGuiWindow ImGuiStorage StateStorage; ImVector_ImGuiOldColumns ColumnsStorage; float FontWindowScale; - float FontDpiScale; + float FontWindowScaleParents; + float FontRefSize; int SettingsOffset; ImDrawList* DrawList; ImDrawList DrawListInst; @@ -3171,8 +3380,6 @@ struct ImGuiWindow ImGuiDockNode* DockNode; ImGuiDockNode* DockNodeAsHost; ImGuiID DockId; - ImGuiItemStatusFlags DockTabItemStatusFlags; - ImRect DockTabItemRect; }; typedef enum { ImGuiTabBarFlags_DockNode = 1 << 20, @@ -3183,7 +3390,8 @@ typedef enum { ImGuiTabItemFlags_SectionMask_ = ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing, ImGuiTabItemFlags_NoCloseButton = 1 << 20, ImGuiTabItemFlags_Button = 1 << 21, - ImGuiTabItemFlags_Unsorted = 1 << 22, + ImGuiTabItemFlags_Invisible = 1 << 22, + ImGuiTabItemFlags_Unsorted = 1 << 23, }ImGuiTabItemFlagsPrivate_; struct ImGuiTabItem { @@ -3205,6 +3413,7 @@ typedef struct ImVector_ImGuiTabItem {int Size;int Capacity;ImGuiTabItem* Data;} struct ImGuiTabBar { + ImGuiWindow* Window; ImVector_ImGuiTabItem Tabs; ImGuiTabBarFlags Flags; ImGuiID ID; @@ -3239,8 +3448,6 @@ struct ImGuiTabBar ImVec2 BackupCursorPos; ImGuiTextBuffer TabsNames; }; -typedef ImS16 ImGuiTableColumnIdx; -typedef ImU16 ImGuiTableDrawChannelIdx; struct ImGuiTableColumn { ImGuiTableColumnFlags Flags; @@ -3249,6 +3456,7 @@ struct ImGuiTableColumn float MaxX; float WidthRequest; float WidthAuto; + float WidthMax; float StretchWeight; float InitStretchWeightOrWidth; ImRect ClipRect; @@ -3411,6 +3619,7 @@ struct ImGuiTable ImGuiTableDrawChannelIdx DummyDrawChannel; ImGuiTableDrawChannelIdx Bg2DrawChannelCurrent; ImGuiTableDrawChannelIdx Bg2DrawChannelUnfrozen; + ImS8 NavLayer; bool IsLayoutLocked; bool IsInsideRow; bool IsInitializing; @@ -3460,7 +3669,7 @@ struct ImGuiTableColumnSettings ImGuiTableColumnIdx DisplayOrder; ImGuiTableColumnIdx SortOrder; ImU8 SortDirection : 2; - ImU8 IsEnabled : 1; + ImS8 IsEnabled : 2; ImU8 IsStretch : 1; }; struct ImGuiTableSettings @@ -3472,10 +3681,92 @@ struct ImGuiTableSettings ImGuiTableColumnIdx ColumnsCountMax; bool WantApply; }; -struct ImFontBuilderIO +struct ImFontLoader { - bool (*FontBuilder_Build)(ImFontAtlas* atlas); + const char* Name; + bool (*LoaderInit)(ImFontAtlas* atlas); + void (*LoaderShutdown)(ImFontAtlas* atlas); + bool (*FontSrcInit)(ImFontAtlas* atlas, ImFontConfig* src); + void (*FontSrcDestroy)(ImFontAtlas* atlas, ImFontConfig* src); + bool (*FontSrcContainsGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint); + bool (*FontBakedInit)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); + void (*FontBakedDestroy)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); + bool (*FontBakedLoadGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph); + size_t FontBakedSrcLoaderDataSize; }; +struct ImFontAtlasRectEntry +{ + int TargetIndex : 20; + int Generation : 10; + unsigned int IsUsed : 1; +}; +struct ImFontAtlasPostProcessData +{ + ImFontAtlas* FontAtlas; + ImFont* Font; + ImFontConfig* FontSrc; + ImFontBaked* FontBaked; + ImFontGlyph* Glyph; + void* Pixels; + ImTextureFormat Format; + int Pitch; + int Width; + int Height; +}; +struct stbrp_node; +typedef stbrp_node stbrp_node_im; +typedef struct stbrp_context_opaque stbrp_context_opaque; +struct stbrp_context_opaque +{ char data[80]; +}; +typedef struct ImVector_stbrp_node_im {int Size;int Capacity;stbrp_node_im* Data;} ImVector_stbrp_node_im; + +typedef struct ImVector_ImFontAtlasRectEntry {int Size;int Capacity;ImFontAtlasRectEntry* Data;} ImVector_ImFontAtlasRectEntry; + +typedef struct ImVector_ImFontBakedPtr {int Size;int Capacity;ImFontBaked** Data;} ImVector_ImFontBakedPtr; + +typedef struct ImStableVector_ImFontBaked__32 {int Size;int Capacity;ImVector_ImFontBakedPtr Blocks;} ImStableVector_ImFontBaked__32; + +struct ImFontAtlasBuilder +{ + stbrp_context_opaque PackContext; + ImVector_stbrp_node_im PackNodes; + ImVector_ImTextureRect Rects; + ImVector_ImFontAtlasRectEntry RectsIndex; + ImVector_unsigned_char TempBuffer; + int RectsIndexFreeListStart; + int RectsPackedCount; + int RectsPackedSurface; + int RectsDiscardedCount; + int RectsDiscardedSurface; + int FrameCount; + ImVec2i MaxRectSize; + ImVec2i MaxRectBounds; + bool LockDisableResize; + bool PreloadedAllGlyphsRanges; + ImStableVector_ImFontBaked__32 BakedPool; + ImGuiStorage BakedMap; + int BakedDiscardedCount; + ImFontAtlasRectId PackIdMouseCursors; + ImFontAtlasRectId PackIdLinesTexData; +}; +#ifdef IMGUI_ENABLE_FREETYPE +struct ImFontAtlas; +struct ImFontLoader; +typedef unsigned int ImGuiFreeTypeLoaderFlags; +typedef enum { + ImGuiFreeTypeLoaderFlags_NoHinting = 1 << 0, + ImGuiFreeTypeLoaderFlags_NoAutoHint = 1 << 1, + ImGuiFreeTypeLoaderFlags_ForceAutoHint = 1 << 2, + ImGuiFreeTypeLoaderFlags_LightHinting = 1 << 3, + ImGuiFreeTypeLoaderFlags_MonoHinting = 1 << 4, + ImGuiFreeTypeLoaderFlags_Bold = 1 << 5, + ImGuiFreeTypeLoaderFlags_Oblique = 1 << 6, + ImGuiFreeTypeLoaderFlags_Monochrome = 1 << 7, + ImGuiFreeTypeLoaderFlags_LoadColor = 1 << 8, + ImGuiFreeTypeLoaderFlags_Bitmap = 1 << 9, +}ImGuiFreeTypeLoaderFlags_; +#endif #define IMGUI_HAS_DOCK 1 #define ImDrawCallback_ResetRenderState (ImDrawCallback)(-8) @@ -3497,15 +3788,20 @@ typedef ImPool ImPool_ImGuiTable; typedef ImSpan ImSpan_ImGuiTableCellData; typedef ImSpan ImSpan_ImGuiTableColumn; typedef ImSpan ImSpan_ImGuiTableColumnIdx; +typedef ImStableVector ImStableVector_ImFontBaked__32; typedef ImVector ImVector_ImDrawChannel; typedef ImVector ImVector_ImDrawCmd; typedef ImVector ImVector_ImDrawIdx; typedef ImVector ImVector_ImDrawListPtr; +typedef ImVector ImVector_ImDrawListSharedDataPtr; typedef ImVector ImVector_ImDrawVert; typedef ImVector ImVector_ImFontPtr; -typedef ImVector ImVector_ImFontAtlasCustomRect; +typedef ImVector ImVector_ImFontAtlasPtr; +typedef ImVector ImVector_ImFontAtlasRectEntry; typedef ImVector ImVector_ImFontConfig; +typedef ImVector ImVector_ImFontConfigPtr; typedef ImVector ImVector_ImFontGlyph; +typedef ImVector ImVector_ImFontStackData; typedef ImVector ImVector_ImGuiColorMod; typedef ImVector ImVector_ImGuiContextHook; typedef ImVector ImVector_ImGuiDockNodeSettings; @@ -3541,8 +3837,12 @@ typedef ImVector ImVector_ImGuiViewportPtr; typedef ImVector ImVector_ImGuiViewportPPtr; typedef ImVector ImVector_ImGuiWindowPtr; typedef ImVector ImVector_ImGuiWindowStackData; -typedef ImVector ImVector_ImTextureID; +typedef ImVector ImVector_ImTextureDataPtr; +typedef ImVector ImVector_ImTextureRect; +typedef ImVector ImVector_ImTextureRef; +typedef ImVector ImVector_ImU16; typedef ImVector ImVector_ImU32; +typedef ImVector ImVector_ImU8; typedef ImVector ImVector_ImVec2; typedef ImVector ImVector_ImVec4; typedef ImVector ImVector_ImWchar; @@ -3550,6 +3850,7 @@ typedef ImVector ImVector_char; typedef ImVector ImVector_const_charPtr; typedef ImVector ImVector_float; typedef ImVector ImVector_int; +typedef ImVector ImVector_stbrp_node_im; typedef ImVector ImVector_unsigned_char; #endif //CIMGUI_DEFINE_ENUMS_AND_STRUCTS CIMGUI_API ImVec2* ImVec2_ImVec2_Nil(void); @@ -3558,11 +3859,16 @@ CIMGUI_API ImVec2* ImVec2_ImVec2_Float(float _x,float _y); CIMGUI_API ImVec4* ImVec4_ImVec4_Nil(void); CIMGUI_API void ImVec4_destroy(ImVec4* self); CIMGUI_API ImVec4* ImVec4_ImVec4_Float(float _x,float _y,float _z,float _w); +CIMGUI_API ImTextureRef* ImTextureRef_ImTextureRef_Nil(void); +CIMGUI_API void ImTextureRef_destroy(ImTextureRef* self); +CIMGUI_API ImTextureRef* ImTextureRef_ImTextureRef_TextureID(ImTextureID tex_id); +CIMGUI_API ImTextureID ImTextureRef_GetTexID(ImTextureRef* self); CIMGUI_API ImGuiContext* igCreateContext(ImFontAtlas* shared_font_atlas); CIMGUI_API void igDestroyContext(ImGuiContext* ctx); CIMGUI_API ImGuiContext* igGetCurrentContext(void); CIMGUI_API void igSetCurrentContext(ImGuiContext* ctx); -CIMGUI_API ImGuiIO* igGetIO(void); +CIMGUI_API ImGuiIO* igGetIO_Nil(void); +CIMGUI_API ImGuiPlatformIO* igGetPlatformIO_Nil(void); CIMGUI_API ImGuiStyle* igGetStyle(void); CIMGUI_API void igNewFrame(void); CIMGUI_API void igEndFrame(void); @@ -3610,7 +3916,6 @@ CIMGUI_API void igSetWindowPos_Vec2(const ImVec2 pos,ImGuiCond cond); CIMGUI_API void igSetWindowSize_Vec2(const ImVec2 size,ImGuiCond cond); CIMGUI_API void igSetWindowCollapsed_Bool(bool collapsed,ImGuiCond cond); CIMGUI_API void igSetWindowFocus_Nil(void); -CIMGUI_API void igSetWindowFontScale(float scale); CIMGUI_API void igSetWindowPos_Str(const char* name,const ImVec2 pos,ImGuiCond cond); CIMGUI_API void igSetWindowSize_Str(const char* name,const ImVec2 size,ImGuiCond cond); CIMGUI_API void igSetWindowCollapsed_Str(const char* name,bool collapsed,ImGuiCond cond); @@ -3625,13 +3930,18 @@ CIMGUI_API void igSetScrollHereX(float center_x_ratio); CIMGUI_API void igSetScrollHereY(float center_y_ratio); CIMGUI_API void igSetScrollFromPosX_Float(float local_x,float center_x_ratio); CIMGUI_API void igSetScrollFromPosY_Float(float local_y,float center_y_ratio); -CIMGUI_API void igPushFont(ImFont* font); +CIMGUI_API void igPushFont(ImFont* font,float font_size_base_unscaled); CIMGUI_API void igPopFont(void); +CIMGUI_API ImFont* igGetFont(void); +CIMGUI_API float igGetFontSize(void); +CIMGUI_API ImFontBaked* igGetFontBaked(void); CIMGUI_API void igPushStyleColor_U32(ImGuiCol idx,ImU32 col); CIMGUI_API void igPushStyleColor_Vec4(ImGuiCol idx,const ImVec4 col); CIMGUI_API void igPopStyleColor(int count); CIMGUI_API void igPushStyleVar_Float(ImGuiStyleVar idx,float val); CIMGUI_API void igPushStyleVar_Vec2(ImGuiStyleVar idx,const ImVec2 val); +CIMGUI_API void igPushStyleVarX(ImGuiStyleVar idx,float val_x); +CIMGUI_API void igPushStyleVarY(ImGuiStyleVar idx,float val_y); CIMGUI_API void igPopStyleVar(int count); CIMGUI_API void igPushItemFlag(ImGuiItemFlags option,bool enabled); CIMGUI_API void igPopItemFlag(void); @@ -3641,8 +3951,6 @@ CIMGUI_API void igSetNextItemWidth(float item_width); CIMGUI_API float igCalcItemWidth(void); CIMGUI_API void igPushTextWrapPos(float wrap_local_pos_x); CIMGUI_API void igPopTextWrapPos(void); -CIMGUI_API ImFont* igGetFont(void); -CIMGUI_API float igGetFontSize(void); CIMGUI_API void igGetFontTexUvWhitePixel(ImVec2 *pOut); CIMGUI_API ImU32 igGetColorU32_Col(ImGuiCol idx,float alpha_mul); CIMGUI_API ImU32 igGetColorU32_Vec4(const ImVec4 col); @@ -3683,16 +3991,34 @@ CIMGUI_API ImGuiID igGetID_Ptr(const void* ptr_id); CIMGUI_API ImGuiID igGetID_Int(int int_id); CIMGUI_API void igTextUnformatted(const char* text,const char* text_end); CIMGUI_API void igText(const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igText0(const char* fmt); +#endif CIMGUI_API void igTextV(const char* fmt,va_list args); CIMGUI_API void igTextColored(const ImVec4 col,const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igTextColored0(const ImVec4 col,const char* fmt); +#endif CIMGUI_API void igTextColoredV(const ImVec4 col,const char* fmt,va_list args); CIMGUI_API void igTextDisabled(const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igTextDisabled0(const char* fmt); +#endif CIMGUI_API void igTextDisabledV(const char* fmt,va_list args); CIMGUI_API void igTextWrapped(const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igTextWrapped0(const char* fmt); +#endif CIMGUI_API void igTextWrappedV(const char* fmt,va_list args); CIMGUI_API void igLabelText(const char* label,const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igLabelText0(const char* label,const char* fmt); +#endif CIMGUI_API void igLabelTextV(const char* label,const char* fmt,va_list args); CIMGUI_API void igBulletText(const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igBulletText0(const char* fmt); +#endif CIMGUI_API void igBulletTextV(const char* fmt,va_list args); CIMGUI_API void igSeparatorText(const char* label); CIMGUI_API bool igButton(const char* label,const ImVec2 size); @@ -3707,9 +4033,10 @@ CIMGUI_API bool igRadioButton_IntPtr(const char* label,int* v,int v_button); CIMGUI_API void igProgressBar(float fraction,const ImVec2 size_arg,const char* overlay); CIMGUI_API void igBullet(void); CIMGUI_API bool igTextLink(const char* label); -CIMGUI_API void igTextLinkOpenURL(const char* label,const char* url); -CIMGUI_API void igImage(ImTextureID user_texture_id,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1); -CIMGUI_API bool igImageButton(const char* str_id,ImTextureID user_texture_id,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1,const ImVec4 bg_col,const ImVec4 tint_col); +CIMGUI_API bool igTextLinkOpenURL(const char* label,const char* url); +CIMGUI_API void igImage(ImTextureRef tex_ref,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1); +CIMGUI_API void igImageWithBg(ImTextureRef tex_ref,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1,const ImVec4 bg_col,const ImVec4 tint_col); +CIMGUI_API bool igImageButton(const char* str_id,ImTextureRef tex_ref,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1,const ImVec4 bg_col,const ImVec4 tint_col); CIMGUI_API bool igBeginCombo(const char* label,const char* preview_value,ImGuiComboFlags flags); CIMGUI_API void igEndCombo(void); CIMGUI_API bool igCombo_Str_arr(const char* label,int* current_item,const char* const items[],int items_count,int popup_max_height_in_items); @@ -3763,12 +4090,24 @@ CIMGUI_API bool igColorButton(const char* desc_id,const ImVec4 col,ImGuiColorEdi CIMGUI_API void igSetColorEditOptions(ImGuiColorEditFlags flags); CIMGUI_API bool igTreeNode_Str(const char* label); CIMGUI_API bool igTreeNode_StrStr(const char* str_id,const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API bool igTreeNode_StrStr0(const char* str_id,const char* fmt); +#endif CIMGUI_API bool igTreeNode_Ptr(const void* ptr_id,const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API bool igTreeNode_Ptr0(const void* ptr_id,const char* fmt); +#endif CIMGUI_API bool igTreeNodeV_Str(const char* str_id,const char* fmt,va_list args); CIMGUI_API bool igTreeNodeV_Ptr(const void* ptr_id,const char* fmt,va_list args); CIMGUI_API bool igTreeNodeEx_Str(const char* label,ImGuiTreeNodeFlags flags); CIMGUI_API bool igTreeNodeEx_StrStr(const char* str_id,ImGuiTreeNodeFlags flags,const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API bool igTreeNodeEx_StrStr0(const char* str_id,ImGuiTreeNodeFlags flags,const char* fmt); +#endif CIMGUI_API bool igTreeNodeEx_Ptr(const void* ptr_id,ImGuiTreeNodeFlags flags,const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API bool igTreeNodeEx_Ptr0(const void* ptr_id,ImGuiTreeNodeFlags flags,const char* fmt); +#endif CIMGUI_API bool igTreeNodeExV_Str(const char* str_id,ImGuiTreeNodeFlags flags,const char* fmt,va_list args); CIMGUI_API bool igTreeNodeExV_Ptr(const void* ptr_id,ImGuiTreeNodeFlags flags,const char* fmt,va_list args); CIMGUI_API void igTreePush_Str(const char* str_id); @@ -3808,9 +4147,15 @@ CIMGUI_API bool igMenuItem_BoolPtr(const char* label,const char* shortcut,bool* CIMGUI_API bool igBeginTooltip(void); CIMGUI_API void igEndTooltip(void); CIMGUI_API void igSetTooltip(const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igSetTooltip0(const char* fmt); +#endif CIMGUI_API void igSetTooltipV(const char* fmt,va_list args); CIMGUI_API bool igBeginItemTooltip(void); CIMGUI_API void igSetItemTooltip(const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igSetItemTooltip0(const char* fmt); +#endif CIMGUI_API void igSetItemTooltipV(const char* fmt,va_list args); CIMGUI_API bool igBeginPopup(const char* str_id,ImGuiWindowFlags flags); CIMGUI_API bool igBeginPopupModal(const char* name,bool* p_open,ImGuiWindowFlags flags); @@ -3842,7 +4187,7 @@ CIMGUI_API ImGuiTableColumnFlags igTableGetColumnFlags(int column_n); CIMGUI_API void igTableSetColumnEnabled(int column_n,bool v); CIMGUI_API int igTableGetHoveredColumn(void); CIMGUI_API void igTableSetBgColor(ImGuiTableBgTarget target,ImU32 color,int column_n); -CIMGUI_API void igColumns(int count,const char* id,bool border); +CIMGUI_API void igColumns(int count,const char* id,bool borders); CIMGUI_API void igNextColumn(void); CIMGUI_API int igGetColumnIndex(void); CIMGUI_API float igGetColumnWidth(int column_index); @@ -3867,6 +4212,10 @@ CIMGUI_API void igLogToFile(int auto_open_depth,const char* filename); CIMGUI_API void igLogToClipboard(int auto_open_depth); CIMGUI_API void igLogFinish(void); CIMGUI_API void igLogButtons(void); +CIMGUI_API void igLogText(const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igLogText0(const char* fmt); +#endif CIMGUI_API void igLogTextV(const char* fmt,va_list args); CIMGUI_API bool igBeginDragDropSource(ImGuiDragDropFlags flags); CIMGUI_API bool igSetDragDropPayload(const char* type,const void* data,size_t sz,ImGuiCond cond); @@ -3881,6 +4230,7 @@ CIMGUI_API void igPushClipRect(const ImVec2 clip_rect_min,const ImVec2 clip_rect CIMGUI_API void igPopClipRect(void); CIMGUI_API void igSetItemDefaultFocus(void); CIMGUI_API void igSetKeyboardFocusHere(int offset); +CIMGUI_API void igSetNavCursorVisible(bool visible); CIMGUI_API void igSetNextItemAllowOverlap(void); CIMGUI_API bool igIsItemHovered(ImGuiHoveredFlags flags); CIMGUI_API bool igIsItemActive(void); @@ -3929,6 +4279,7 @@ CIMGUI_API bool igIsMouseDown_Nil(ImGuiMouseButton button); CIMGUI_API bool igIsMouseClicked_Bool(ImGuiMouseButton button,bool repeat); CIMGUI_API bool igIsMouseReleased_Nil(ImGuiMouseButton button); CIMGUI_API bool igIsMouseDoubleClicked_Nil(ImGuiMouseButton button); +CIMGUI_API bool igIsMouseReleasedWithDelay(ImGuiMouseButton button,float delay); CIMGUI_API int igGetMouseClickedCount(ImGuiMouseButton button); CIMGUI_API bool igIsMouseHoveringRect(const ImVec2 r_min,const ImVec2 r_max,bool clip); CIMGUI_API bool igIsMousePosValid(const ImVec2* mouse_pos); @@ -3952,12 +4303,14 @@ CIMGUI_API void igDebugFlashStyleColor(ImGuiCol idx); CIMGUI_API void igDebugStartItemPicker(void); CIMGUI_API bool igDebugCheckVersionAndDataLayout(const char* version_str,size_t sz_io,size_t sz_style,size_t sz_vec2,size_t sz_vec4,size_t sz_drawvert,size_t sz_drawidx); CIMGUI_API void igDebugLog(const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igDebugLog0(const char* fmt); +#endif CIMGUI_API void igDebugLogV(const char* fmt,va_list args); CIMGUI_API void igSetAllocatorFunctions(ImGuiMemAllocFunc alloc_func,ImGuiMemFreeFunc free_func,void* user_data); CIMGUI_API void igGetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func,ImGuiMemFreeFunc* p_free_func,void** p_user_data); CIMGUI_API void* igMemAlloc(size_t size); CIMGUI_API void igMemFree(void* ptr); -CIMGUI_API ImGuiPlatformIO* igGetPlatformIO(void); CIMGUI_API void igUpdatePlatformWindows(void); CIMGUI_API void igRenderPlatformWindowsDefault(void* platform_render_arg,void* renderer_render_arg); CIMGUI_API void igDestroyPlatformWindows(void); @@ -4024,6 +4377,7 @@ CIMGUI_API const char* ImGuiTextBuffer_end(ImGuiTextBuffer* self); CIMGUI_API int ImGuiTextBuffer_size(ImGuiTextBuffer* self); CIMGUI_API bool ImGuiTextBuffer_empty(ImGuiTextBuffer* self); CIMGUI_API void ImGuiTextBuffer_clear(ImGuiTextBuffer* self); +CIMGUI_API void ImGuiTextBuffer_resize(ImGuiTextBuffer* self,int size); CIMGUI_API void ImGuiTextBuffer_reserve(ImGuiTextBuffer* self,int capacity); CIMGUI_API const char* ImGuiTextBuffer_c_str(ImGuiTextBuffer* self); CIMGUI_API void ImGuiTextBuffer_append(ImGuiTextBuffer* self,const char* str,const char* str_end); @@ -4090,8 +4444,8 @@ CIMGUI_API void ImDrawList_destroy(ImDrawList* self); CIMGUI_API void ImDrawList_PushClipRect(ImDrawList* self,const ImVec2 clip_rect_min,const ImVec2 clip_rect_max,bool intersect_with_current_clip_rect); CIMGUI_API void ImDrawList_PushClipRectFullScreen(ImDrawList* self); CIMGUI_API void ImDrawList_PopClipRect(ImDrawList* self); -CIMGUI_API void ImDrawList_PushTextureID(ImDrawList* self,ImTextureID texture_id); -CIMGUI_API void ImDrawList_PopTextureID(ImDrawList* self); +CIMGUI_API void ImDrawList_PushTexture(ImDrawList* self,ImTextureRef tex_ref); +CIMGUI_API void ImDrawList_PopTexture(ImDrawList* self); CIMGUI_API void ImDrawList_GetClipRectMin(ImVec2 *pOut,ImDrawList* self); CIMGUI_API void ImDrawList_GetClipRectMax(ImVec2 *pOut,ImDrawList* self); CIMGUI_API void ImDrawList_AddLine(ImDrawList* self,const ImVec2 p1,const ImVec2 p2,ImU32 col,float thickness); @@ -4115,9 +4469,9 @@ CIMGUI_API void ImDrawList_AddBezierQuadratic(ImDrawList* self,const ImVec2 p1,c CIMGUI_API void ImDrawList_AddPolyline(ImDrawList* self,const ImVec2* points,int num_points,ImU32 col,ImDrawFlags flags,float thickness); CIMGUI_API void ImDrawList_AddConvexPolyFilled(ImDrawList* self,const ImVec2* points,int num_points,ImU32 col); CIMGUI_API void ImDrawList_AddConcavePolyFilled(ImDrawList* self,const ImVec2* points,int num_points,ImU32 col); -CIMGUI_API void ImDrawList_AddImage(ImDrawList* self,ImTextureID user_texture_id,const ImVec2 p_min,const ImVec2 p_max,const ImVec2 uv_min,const ImVec2 uv_max,ImU32 col); -CIMGUI_API void ImDrawList_AddImageQuad(ImDrawList* self,ImTextureID user_texture_id,const ImVec2 p1,const ImVec2 p2,const ImVec2 p3,const ImVec2 p4,const ImVec2 uv1,const ImVec2 uv2,const ImVec2 uv3,const ImVec2 uv4,ImU32 col); -CIMGUI_API void ImDrawList_AddImageRounded(ImDrawList* self,ImTextureID user_texture_id,const ImVec2 p_min,const ImVec2 p_max,const ImVec2 uv_min,const ImVec2 uv_max,ImU32 col,float rounding,ImDrawFlags flags); +CIMGUI_API void ImDrawList_AddImage(ImDrawList* self,ImTextureRef tex_ref,const ImVec2 p_min,const ImVec2 p_max,const ImVec2 uv_min,const ImVec2 uv_max,ImU32 col); +CIMGUI_API void ImDrawList_AddImageQuad(ImDrawList* self,ImTextureRef tex_ref,const ImVec2 p1,const ImVec2 p2,const ImVec2 p3,const ImVec2 p4,const ImVec2 uv1,const ImVec2 uv2,const ImVec2 uv3,const ImVec2 uv4,ImU32 col); +CIMGUI_API void ImDrawList_AddImageRounded(ImDrawList* self,ImTextureRef tex_ref,const ImVec2 p_min,const ImVec2 p_max,const ImVec2 uv_min,const ImVec2 uv_max,ImU32 col,float rounding,ImDrawFlags flags); CIMGUI_API void ImDrawList_PathClear(ImDrawList* self); CIMGUI_API void ImDrawList_PathLineTo(ImDrawList* self,const ImVec2 pos); CIMGUI_API void ImDrawList_PathLineToMergeDuplicate(ImDrawList* self,const ImVec2 pos); @@ -4130,7 +4484,7 @@ CIMGUI_API void ImDrawList_PathEllipticalArcTo(ImDrawList* self,const ImVec2 cen CIMGUI_API void ImDrawList_PathBezierCubicCurveTo(ImDrawList* self,const ImVec2 p2,const ImVec2 p3,const ImVec2 p4,int num_segments); CIMGUI_API void ImDrawList_PathBezierQuadraticCurveTo(ImDrawList* self,const ImVec2 p2,const ImVec2 p3,int num_segments); CIMGUI_API void ImDrawList_PathRect(ImDrawList* self,const ImVec2 rect_min,const ImVec2 rect_max,float rounding,ImDrawFlags flags); -CIMGUI_API void ImDrawList_AddCallback(ImDrawList* self,ImDrawCallback callback,void* callback_data); +CIMGUI_API void ImDrawList_AddCallback(ImDrawList* self,ImDrawCallback callback,void* userdata,size_t userdata_size); CIMGUI_API void ImDrawList_AddDrawCmd(ImDrawList* self); CIMGUI_API ImDrawList* ImDrawList_CloneOutput(ImDrawList* self); CIMGUI_API void ImDrawList_ChannelsSplit(ImDrawList* self,int count); @@ -4144,13 +4498,15 @@ CIMGUI_API void ImDrawList_PrimQuadUV(ImDrawList* self,const ImVec2 a,const ImVe CIMGUI_API void ImDrawList_PrimWriteVtx(ImDrawList* self,const ImVec2 pos,const ImVec2 uv,ImU32 col); CIMGUI_API void ImDrawList_PrimWriteIdx(ImDrawList* self,ImDrawIdx idx); CIMGUI_API void ImDrawList_PrimVtx(ImDrawList* self,const ImVec2 pos,const ImVec2 uv,ImU32 col); +CIMGUI_API void ImDrawList__SetDrawListSharedData(ImDrawList* self,ImDrawListSharedData* data); CIMGUI_API void ImDrawList__ResetForNewFrame(ImDrawList* self); CIMGUI_API void ImDrawList__ClearFreeMemory(ImDrawList* self); CIMGUI_API void ImDrawList__PopUnusedDrawCmd(ImDrawList* self); CIMGUI_API void ImDrawList__TryMergeDrawCmds(ImDrawList* self); CIMGUI_API void ImDrawList__OnChangedClipRect(ImDrawList* self); -CIMGUI_API void ImDrawList__OnChangedTextureID(ImDrawList* self); +CIMGUI_API void ImDrawList__OnChangedTexture(ImDrawList* self); CIMGUI_API void ImDrawList__OnChangedVtxOffset(ImDrawList* self); +CIMGUI_API void ImDrawList__SetTexture(ImDrawList* self,ImTextureRef tex_ref); CIMGUI_API int ImDrawList__CalcCircleAutoSegmentCount(ImDrawList* self,float radius); CIMGUI_API void ImDrawList__PathArcToFastEx(ImDrawList* self,const ImVec2 center,float radius,int a_min_sample,int a_max_sample,int a_step); CIMGUI_API void ImDrawList__PathArcToN(ImDrawList* self,const ImVec2 center,float radius,float a_min,float a_max,int num_segments); @@ -4160,8 +4516,22 @@ CIMGUI_API void ImDrawData_Clear(ImDrawData* self); CIMGUI_API void ImDrawData_AddDrawList(ImDrawData* self,ImDrawList* draw_list); CIMGUI_API void ImDrawData_DeIndexAllBuffers(ImDrawData* self); CIMGUI_API void ImDrawData_ScaleClipRects(ImDrawData* self,const ImVec2 fb_scale); +CIMGUI_API ImTextureData* ImTextureData_ImTextureData(void); +CIMGUI_API void ImTextureData_destroy(ImTextureData* self); +CIMGUI_API void ImTextureData_Create(ImTextureData* self,ImTextureFormat format,int w,int h); +CIMGUI_API void ImTextureData_DestroyPixels(ImTextureData* self); +CIMGUI_API void* ImTextureData_GetPixels(ImTextureData* self); +CIMGUI_API void* ImTextureData_GetPixelsAt(ImTextureData* self,int x,int y); +CIMGUI_API int ImTextureData_GetSizeInBytes(ImTextureData* self); +CIMGUI_API int ImTextureData_GetPitch(ImTextureData* self); +CIMGUI_API void ImTextureData_GetTexRef(ImTextureRef *pOut,ImTextureData* self); +CIMGUI_API ImTextureID ImTextureData_GetTexID(ImTextureData* self); +CIMGUI_API void ImTextureData_SetTexID(ImTextureData* self,ImTextureID tex_id); +CIMGUI_API void ImTextureData_SetStatus(ImTextureData* self,ImTextureStatus status); CIMGUI_API ImFontConfig* ImFontConfig_ImFontConfig(void); CIMGUI_API void ImFontConfig_destroy(ImFontConfig* self); +CIMGUI_API ImFontGlyph* ImFontGlyph_ImFontGlyph(void); +CIMGUI_API void ImFontGlyph_destroy(ImFontGlyph* self); CIMGUI_API ImFontGlyphRangesBuilder* ImFontGlyphRangesBuilder_ImFontGlyphRangesBuilder(void); CIMGUI_API void ImFontGlyphRangesBuilder_destroy(ImFontGlyphRangesBuilder* self); CIMGUI_API void ImFontGlyphRangesBuilder_Clear(ImFontGlyphRangesBuilder* self); @@ -4171,9 +4541,8 @@ CIMGUI_API void ImFontGlyphRangesBuilder_AddChar(ImFontGlyphRangesBuilder* self, CIMGUI_API void ImFontGlyphRangesBuilder_AddText(ImFontGlyphRangesBuilder* self,const char* text,const char* text_end); CIMGUI_API void ImFontGlyphRangesBuilder_AddRanges(ImFontGlyphRangesBuilder* self,const ImWchar* ranges); CIMGUI_API void ImFontGlyphRangesBuilder_BuildRanges(ImFontGlyphRangesBuilder* self,ImVector_ImWchar* out_ranges); -CIMGUI_API ImFontAtlasCustomRect* ImFontAtlasCustomRect_ImFontAtlasCustomRect(void); -CIMGUI_API void ImFontAtlasCustomRect_destroy(ImFontAtlasCustomRect* self); -CIMGUI_API bool ImFontAtlasCustomRect_IsPacked(ImFontAtlasCustomRect* self); +CIMGUI_API ImFontAtlasRect* ImFontAtlasRect_ImFontAtlasRect(void); +CIMGUI_API void ImFontAtlasRect_destroy(ImFontAtlasRect* self); CIMGUI_API ImFontAtlas* ImFontAtlas_ImFontAtlas(void); CIMGUI_API void ImFontAtlas_destroy(ImFontAtlas* self); CIMGUI_API ImFont* ImFontAtlas_AddFont(ImFontAtlas* self,const ImFontConfig* font_cfg); @@ -4182,46 +4551,35 @@ CIMGUI_API ImFont* ImFontAtlas_AddFontFromFileTTF(ImFontAtlas* self,const char* CIMGUI_API ImFont* ImFontAtlas_AddFontFromMemoryTTF(ImFontAtlas* self,void* font_data,int font_data_size,float size_pixels,const ImFontConfig* font_cfg,const ImWchar* glyph_ranges); CIMGUI_API ImFont* ImFontAtlas_AddFontFromMemoryCompressedTTF(ImFontAtlas* self,const void* compressed_font_data,int compressed_font_data_size,float size_pixels,const ImFontConfig* font_cfg,const ImWchar* glyph_ranges); CIMGUI_API ImFont* ImFontAtlas_AddFontFromMemoryCompressedBase85TTF(ImFontAtlas* self,const char* compressed_font_data_base85,float size_pixels,const ImFontConfig* font_cfg,const ImWchar* glyph_ranges); -CIMGUI_API void ImFontAtlas_ClearInputData(ImFontAtlas* self); -CIMGUI_API void ImFontAtlas_ClearTexData(ImFontAtlas* self); -CIMGUI_API void ImFontAtlas_ClearFonts(ImFontAtlas* self); +CIMGUI_API void ImFontAtlas_RemoveFont(ImFontAtlas* self,ImFont* font); CIMGUI_API void ImFontAtlas_Clear(ImFontAtlas* self); -CIMGUI_API bool ImFontAtlas_Build(ImFontAtlas* self); -CIMGUI_API void ImFontAtlas_GetTexDataAsAlpha8(ImFontAtlas* self,unsigned char** out_pixels,int* out_width,int* out_height,int* out_bytes_per_pixel); -CIMGUI_API void ImFontAtlas_GetTexDataAsRGBA32(ImFontAtlas* self,unsigned char** out_pixels,int* out_width,int* out_height,int* out_bytes_per_pixel); -CIMGUI_API bool ImFontAtlas_IsBuilt(ImFontAtlas* self); -CIMGUI_API void ImFontAtlas_SetTexID(ImFontAtlas* self,ImTextureID id); +CIMGUI_API void ImFontAtlas_CompactCache(ImFontAtlas* self); +CIMGUI_API void ImFontAtlas_ClearInputData(ImFontAtlas* self); +CIMGUI_API void ImFontAtlas_ClearFonts(ImFontAtlas* self); +CIMGUI_API void ImFontAtlas_ClearTexData(ImFontAtlas* self); CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesDefault(ImFontAtlas* self); -CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesGreek(ImFontAtlas* self); -CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesKorean(ImFontAtlas* self); -CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesJapanese(ImFontAtlas* self); -CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesChineseFull(ImFontAtlas* self); -CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesChineseSimplifiedCommon(ImFontAtlas* self); -CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesCyrillic(ImFontAtlas* self); -CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesThai(ImFontAtlas* self); -CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesVietnamese(ImFontAtlas* self); -CIMGUI_API int ImFontAtlas_AddCustomRectRegular(ImFontAtlas* self,int width,int height); -CIMGUI_API int ImFontAtlas_AddCustomRectFontGlyph(ImFontAtlas* self,ImFont* font,ImWchar id,int width,int height,float advance_x,const ImVec2 offset); -CIMGUI_API ImFontAtlasCustomRect* ImFontAtlas_GetCustomRectByIndex(ImFontAtlas* self,int index); -CIMGUI_API void ImFontAtlas_CalcCustomRectUV(ImFontAtlas* self,const ImFontAtlasCustomRect* rect,ImVec2* out_uv_min,ImVec2* out_uv_max); -CIMGUI_API bool ImFontAtlas_GetMouseCursorTexData(ImFontAtlas* self,ImGuiMouseCursor cursor,ImVec2* out_offset,ImVec2* out_size,ImVec2 out_uv_border[2],ImVec2 out_uv_fill[2]); +CIMGUI_API ImFontAtlasRectId ImFontAtlas_AddCustomRect(ImFontAtlas* self,int width,int height,ImFontAtlasRect* out_r); +CIMGUI_API void ImFontAtlas_RemoveCustomRect(ImFontAtlas* self,ImFontAtlasRectId id); +CIMGUI_API bool ImFontAtlas_GetCustomRect(ImFontAtlas* self,ImFontAtlasRectId id,ImFontAtlasRect* out_r); +CIMGUI_API ImFontBaked* ImFontBaked_ImFontBaked(void); +CIMGUI_API void ImFontBaked_destroy(ImFontBaked* self); +CIMGUI_API void ImFontBaked_ClearOutputData(ImFontBaked* self); +CIMGUI_API ImFontGlyph* ImFontBaked_FindGlyph(ImFontBaked* self,ImWchar c); +CIMGUI_API ImFontGlyph* ImFontBaked_FindGlyphNoFallback(ImFontBaked* self,ImWchar c); +CIMGUI_API float ImFontBaked_GetCharAdvance(ImFontBaked* self,ImWchar c); +CIMGUI_API bool ImFontBaked_IsGlyphLoaded(ImFontBaked* self,ImWchar c); CIMGUI_API ImFont* ImFont_ImFont(void); CIMGUI_API void ImFont_destroy(ImFont* self); -CIMGUI_API const ImFontGlyph* ImFont_FindGlyph(ImFont* self,ImWchar c); -CIMGUI_API const ImFontGlyph* ImFont_FindGlyphNoFallback(ImFont* self,ImWchar c); -CIMGUI_API float ImFont_GetCharAdvance(ImFont* self,ImWchar c); +CIMGUI_API bool ImFont_IsGlyphInFont(ImFont* self,ImWchar c); CIMGUI_API bool ImFont_IsLoaded(ImFont* self); CIMGUI_API const char* ImFont_GetDebugName(ImFont* self); +CIMGUI_API ImFontBaked* ImFont_GetFontBaked(ImFont* self,float font_size,float density); CIMGUI_API void ImFont_CalcTextSizeA(ImVec2 *pOut,ImFont* self,float size,float max_width,float wrap_width,const char* text_begin,const char* text_end,const char** remaining); -CIMGUI_API const char* ImFont_CalcWordWrapPositionA(ImFont* self,float scale,const char* text,const char* text_end,float wrap_width); -CIMGUI_API void ImFont_RenderChar(ImFont* self,ImDrawList* draw_list,float size,const ImVec2 pos,ImU32 col,ImWchar c); +CIMGUI_API const char* ImFont_CalcWordWrapPosition(ImFont* self,float size,const char* text,const char* text_end,float wrap_width); +CIMGUI_API void ImFont_RenderChar(ImFont* self,ImDrawList* draw_list,float size,const ImVec2 pos,ImU32 col,ImWchar c,const ImVec4* cpu_fine_clip); CIMGUI_API void ImFont_RenderText(ImFont* self,ImDrawList* draw_list,float size,const ImVec2 pos,ImU32 col,const ImVec4 clip_rect,const char* text_begin,const char* text_end,float wrap_width,bool cpu_fine_clip); -CIMGUI_API void ImFont_BuildLookupTable(ImFont* self); CIMGUI_API void ImFont_ClearOutputData(ImFont* self); -CIMGUI_API void ImFont_GrowIndex(ImFont* self,int new_size); -CIMGUI_API void ImFont_AddGlyph(ImFont* self,const ImFontConfig* src_cfg,ImWchar c,float x0,float y0,float x1,float y1,float u0,float v0,float u1,float v1,float advance_x); -CIMGUI_API void ImFont_AddRemapChar(ImFont* self,ImWchar dst,ImWchar src,bool overwrite_dst); -CIMGUI_API void ImFont_SetGlyphVisible(ImFont* self,ImWchar c,bool visible); +CIMGUI_API void ImFont_AddRemapChar(ImFont* self,ImWchar from_codepoint,ImWchar to_codepoint); CIMGUI_API bool ImFont_IsGlyphRangeUnused(ImFont* self,unsigned int c_begin,unsigned int c_last); CIMGUI_API ImGuiViewport* ImGuiViewport_ImGuiViewport(void); CIMGUI_API void ImGuiViewport_destroy(ImGuiViewport* self); @@ -4235,15 +4593,17 @@ CIMGUI_API ImGuiPlatformImeData* ImGuiPlatformImeData_ImGuiPlatformImeData(void) CIMGUI_API void ImGuiPlatformImeData_destroy(ImGuiPlatformImeData* self); CIMGUI_API ImGuiID igImHashData(const void* data,size_t data_size,ImGuiID seed); CIMGUI_API ImGuiID igImHashStr(const char* data,size_t data_size,ImGuiID seed); -CIMGUI_API void igImQsort(void* base,size_t count,size_t size_of_element,int(*compare_func)(const void*, const void*)); +CIMGUI_API void igImQsort(void* base,size_t count,size_t size_of_element,int(*compare_func)(void const*,void const*)); CIMGUI_API ImU32 igImAlphaBlendColors(ImU32 col_a,ImU32 col_b); CIMGUI_API bool igImIsPowerOfTwo_Int(int v); CIMGUI_API bool igImIsPowerOfTwo_U64(ImU64 v); CIMGUI_API int igImUpperPowerOfTwo(int v); +CIMGUI_API unsigned int igImCountSetBits(unsigned int v); CIMGUI_API int igImStricmp(const char* str1,const char* str2); CIMGUI_API int igImStrnicmp(const char* str1,const char* str2,size_t count); CIMGUI_API void igImStrncpy(char* dst,const char* src,size_t count); CIMGUI_API char* igImStrdup(const char* str); +CIMGUI_API void* igImMemdup(const void* src,size_t size); CIMGUI_API char* igImStrdupcpy(char* dst,size_t* p_dst_size,const char* str); CIMGUI_API const char* igImStrchrRange(const char* str_begin,const char* str_end,char c); CIMGUI_API const char* igImStreolRange(const char* str,const char* str_end); @@ -4251,14 +4611,20 @@ CIMGUI_API const char* igImStristr(const char* haystack,const char* haystack_end CIMGUI_API void igImStrTrimBlanks(char* str); CIMGUI_API const char* igImStrSkipBlank(const char* str); CIMGUI_API int igImStrlenW(const ImWchar* str); -CIMGUI_API const ImWchar* igImStrbolW(const ImWchar* buf_mid_line,const ImWchar* buf_begin); +CIMGUI_API const char* igImStrbol(const char* buf_mid_line,const char* buf_begin); CIMGUI_API char igImToUpper(char c); CIMGUI_API bool igImCharIsBlankA(char c); CIMGUI_API bool igImCharIsBlankW(unsigned int c); CIMGUI_API bool igImCharIsXdigitA(char c); CIMGUI_API int igImFormatString(char* buf,size_t buf_size,const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API int igImFormatString0(char* buf,size_t buf_size,const char* fmt); +#endif CIMGUI_API int igImFormatStringV(char* buf,size_t buf_size,const char* fmt,va_list args); CIMGUI_API void igImFormatStringToTempBuffer(const char** out_buf,const char** out_buf_end,const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igImFormatStringToTempBuffer0(const char** out_buf,const char** out_buf_end,const char* fmt); +#endif CIMGUI_API void igImFormatStringToTempBufferV(const char** out_buf,const char** out_buf_end,const char* fmt,va_list args); CIMGUI_API const char* igImParseFormatFindStart(const char* format); CIMGUI_API const char* igImParseFormatFindEnd(const char* format); @@ -4306,6 +4672,8 @@ CIMGUI_API float igImTrunc_Float(float f); CIMGUI_API void igImTrunc_Vec2(ImVec2 *pOut,const ImVec2 v); CIMGUI_API float igImFloor_Float(float f); CIMGUI_API void igImFloor_Vec2(ImVec2 *pOut,const ImVec2 v); +CIMGUI_API float igImTrunc64(float f); +CIMGUI_API float igImRound64(float f); CIMGUI_API int igImModPositive(int a,int b); CIMGUI_API float igImDot(const ImVec2 a,const ImVec2 b); CIMGUI_API void igImRotate(ImVec2 *pOut,const ImVec2 v,float cos_a,float sin_a); @@ -4327,6 +4695,9 @@ CIMGUI_API bool igImTriangleIsClockwise(const ImVec2 a,const ImVec2 b,const ImVe CIMGUI_API ImVec1* ImVec1_ImVec1_Nil(void); CIMGUI_API void ImVec1_destroy(ImVec1* self); CIMGUI_API ImVec1* ImVec1_ImVec1_Float(float _x); +CIMGUI_API ImVec2i* ImVec2i_ImVec2i_Nil(void); +CIMGUI_API void ImVec2i_destroy(ImVec2i* self); +CIMGUI_API ImVec2i* ImVec2i_ImVec2i_Int(int _x,int _y); CIMGUI_API ImVec2ih* ImVec2ih_ImVec2ih_Nil(void); CIMGUI_API void ImVec2ih_destroy(ImVec2ih* self); CIMGUI_API ImVec2ih* ImVec2ih_ImVec2ih_short(short _x,short _y); @@ -4403,6 +4774,7 @@ CIMGUI_API void ImGuiInputTextState_destroy(ImGuiInputTextState* self); CIMGUI_API void ImGuiInputTextState_ClearText(ImGuiInputTextState* self); CIMGUI_API void ImGuiInputTextState_ClearFreeMemory(ImGuiInputTextState* self); CIMGUI_API void ImGuiInputTextState_OnKeyPressed(ImGuiInputTextState* self,int key); +CIMGUI_API void ImGuiInputTextState_OnCharPressed(ImGuiInputTextState* self,unsigned int c); CIMGUI_API void ImGuiInputTextState_CursorAnimReset(ImGuiInputTextState* self); CIMGUI_API void ImGuiInputTextState_CursorClamp(ImGuiInputTextState* self); CIMGUI_API bool ImGuiInputTextState_HasSelection(ImGuiInputTextState* self); @@ -4422,6 +4794,8 @@ CIMGUI_API void ImGuiNextItemData_destroy(ImGuiNextItemData* self); CIMGUI_API void ImGuiNextItemData_ClearFlags(ImGuiNextItemData* self); CIMGUI_API ImGuiLastItemData* ImGuiLastItemData_ImGuiLastItemData(void); CIMGUI_API void ImGuiLastItemData_destroy(ImGuiLastItemData* self); +CIMGUI_API ImGuiErrorRecoveryState* ImGuiErrorRecoveryState_ImGuiErrorRecoveryState(void); +CIMGUI_API void ImGuiErrorRecoveryState_destroy(ImGuiErrorRecoveryState* self); CIMGUI_API ImGuiPtrOrIndex* ImGuiPtrOrIndex_ImGuiPtrOrIndex_Ptr(void* ptr); CIMGUI_API void ImGuiPtrOrIndex_destroy(ImGuiPtrOrIndex* self); CIMGUI_API ImGuiPtrOrIndex* ImGuiPtrOrIndex_ImGuiPtrOrIndex_Int(int index); @@ -4478,8 +4852,8 @@ CIMGUI_API void ImGuiDockContext_destroy(ImGuiDockContext* self); CIMGUI_API ImGuiViewportP* ImGuiViewportP_ImGuiViewportP(void); CIMGUI_API void ImGuiViewportP_destroy(ImGuiViewportP* self); CIMGUI_API void ImGuiViewportP_ClearRequestFlags(ImGuiViewportP* self); -CIMGUI_API void ImGuiViewportP_CalcWorkRectPos(ImVec2 *pOut,ImGuiViewportP* self,const ImVec2 off_min); -CIMGUI_API void ImGuiViewportP_CalcWorkRectSize(ImVec2 *pOut,ImGuiViewportP* self,const ImVec2 off_min,const ImVec2 off_max); +CIMGUI_API void ImGuiViewportP_CalcWorkRectPos(ImVec2 *pOut,ImGuiViewportP* self,const ImVec2 inset_min); +CIMGUI_API void ImGuiViewportP_CalcWorkRectSize(ImVec2 *pOut,ImGuiViewportP* self,const ImVec2 inset_min,const ImVec2 inset_max); CIMGUI_API void ImGuiViewportP_UpdateWorkRect(ImGuiViewportP* self); CIMGUI_API void ImGuiViewportP_GetMainRect(ImRect *pOut,ImGuiViewportP* self); CIMGUI_API void ImGuiViewportP_GetWorkRect(ImRect *pOut,ImGuiViewportP* self); @@ -4504,9 +4878,9 @@ CIMGUI_API void ImGuiWindow_destroy(ImGuiWindow* self); CIMGUI_API ImGuiID ImGuiWindow_GetID_Str(ImGuiWindow* self,const char* str,const char* str_end); CIMGUI_API ImGuiID ImGuiWindow_GetID_Ptr(ImGuiWindow* self,const void* ptr); CIMGUI_API ImGuiID ImGuiWindow_GetID_Int(ImGuiWindow* self,int n); +CIMGUI_API ImGuiID ImGuiWindow_GetIDFromPos(ImGuiWindow* self,const ImVec2 p_abs); CIMGUI_API ImGuiID ImGuiWindow_GetIDFromRectangle(ImGuiWindow* self,const ImRect r_abs); CIMGUI_API void ImGuiWindow_Rect(ImRect *pOut,ImGuiWindow* self); -CIMGUI_API float ImGuiWindow_CalcFontSize(ImGuiWindow* self); CIMGUI_API void ImGuiWindow_TitleBarRect(ImRect *pOut,ImGuiWindow* self); CIMGUI_API void ImGuiWindow_MenuBarRect(ImRect *pOut,ImGuiWindow* self); CIMGUI_API ImGuiTabItem* ImGuiTabItem_ImGuiTabItem(void); @@ -4526,6 +4900,8 @@ CIMGUI_API void ImGuiTableColumnSettings_destroy(ImGuiTableColumnSettings* self) CIMGUI_API ImGuiTableSettings* ImGuiTableSettings_ImGuiTableSettings(void); CIMGUI_API void ImGuiTableSettings_destroy(ImGuiTableSettings* self); CIMGUI_API ImGuiTableColumnSettings* ImGuiTableSettings_GetColumnSettings(ImGuiTableSettings* self); +CIMGUI_API ImGuiIO* igGetIO_ContextPtr(ImGuiContext* ctx); +CIMGUI_API ImGuiPlatformIO* igGetPlatformIO_ContextPtr(ImGuiContext* ctx); CIMGUI_API ImGuiWindow* igGetCurrentWindowRead(void); CIMGUI_API ImGuiWindow* igGetCurrentWindow(void); CIMGUI_API ImGuiWindow* igFindWindowByID(ImGuiID id); @@ -4545,8 +4921,8 @@ CIMGUI_API void igSetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window CIMGUI_API void igSetWindowParentWindowForFocusRoute(ImGuiWindow* window,ImGuiWindow* parent_window); CIMGUI_API void igWindowRectAbsToRel(ImRect *pOut,ImGuiWindow* window,const ImRect r); CIMGUI_API void igWindowRectRelToAbs(ImRect *pOut,ImGuiWindow* window,const ImRect r); -CIMGUI_API void igWindowPosRelToAbs(ImVec2 *pOut,ImGuiWindow* window,const ImVec2 p); CIMGUI_API void igWindowPosAbsToRel(ImVec2 *pOut,ImGuiWindow* window,const ImVec2 p); +CIMGUI_API void igWindowPosRelToAbs(ImVec2 *pOut,ImGuiWindow* window,const ImVec2 p); CIMGUI_API void igFocusWindow(ImGuiWindow* window,ImGuiFocusRequestFlags flags); CIMGUI_API void igFocusTopMostWindowUnderOne(ImGuiWindow* under_this_window,ImGuiWindow* ignore_window,ImGuiViewport* filter_viewport,ImGuiFocusRequestFlags flags); CIMGUI_API void igBringWindowToFocusFront(ImGuiWindow* window); @@ -4556,14 +4932,24 @@ CIMGUI_API void igBringWindowToDisplayBehind(ImGuiWindow* window,ImGuiWindow* ab CIMGUI_API int igFindWindowDisplayIndex(ImGuiWindow* window); CIMGUI_API ImGuiWindow* igFindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* window); CIMGUI_API void igSetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags); -CIMGUI_API void igSetCurrentFont(ImFont* font); +CIMGUI_API void igRegisterUserTexture(ImTextureData* tex); +CIMGUI_API void igUnregisterUserTexture(ImTextureData* tex); +CIMGUI_API void igRegisterFontAtlas(ImFontAtlas* atlas); +CIMGUI_API void igUnregisterFontAtlas(ImFontAtlas* atlas); +CIMGUI_API void igSetCurrentFont(ImFont* font,float font_size_before_scaling,float font_size_after_scaling); +CIMGUI_API void igUpdateCurrentFontSize(float restore_font_size_after_scaling); +CIMGUI_API void igSetFontRasterizerDensity(float rasterizer_density); +CIMGUI_API float igGetFontRasterizerDensity(void); +CIMGUI_API float igGetRoundedFontSize(float size); CIMGUI_API ImFont* igGetDefaultFont(void); +CIMGUI_API void igPushPasswordFont(void); +CIMGUI_API void igPopPasswordFont(void); CIMGUI_API ImDrawList* igGetForegroundDrawList_WindowPtr(ImGuiWindow* window); CIMGUI_API void igAddDrawListToDrawDataEx(ImDrawData* draw_data,ImVector_ImDrawListPtr* out_list,ImDrawList* draw_list); CIMGUI_API void igInitialize(void); CIMGUI_API void igShutdown(void); CIMGUI_API void igUpdateInputEvents(bool trickle_fast_inputs); -CIMGUI_API void igUpdateHoveredWindowAndCaptureFlags(void); +CIMGUI_API void igUpdateHoveredWindowAndCaptureFlags(const ImVec2 mouse_pos); CIMGUI_API void igFindHoveredWindowEx(const ImVec2 pos,bool find_first_and_in_any_viewport,ImGuiWindow** out_hovered_window,ImGuiWindow** out_hovered_window_under_moving_window); CIMGUI_API void igStartMouseMovingWindow(ImGuiWindow* window); CIMGUI_API void igStartMouseMovingWindowOrNode(ImGuiWindow* window,ImGuiDockNode* node,bool undock); @@ -4619,7 +5005,7 @@ CIMGUI_API bool igItemAdd(const ImRect bb,ImGuiID id,const ImRect* nav_bb,ImGuiI CIMGUI_API bool igItemHoverable(const ImRect bb,ImGuiID id,ImGuiItemFlags item_flags); CIMGUI_API bool igIsWindowContentHoverable(ImGuiWindow* window,ImGuiHoveredFlags flags); CIMGUI_API bool igIsClippedEx(const ImRect bb,ImGuiID id); -CIMGUI_API void igSetLastItemData(ImGuiID item_id,ImGuiItemFlags in_flags,ImGuiItemStatusFlags status_flags,const ImRect item_rect); +CIMGUI_API void igSetLastItemData(ImGuiID item_id,ImGuiItemFlags item_flags,ImGuiItemStatusFlags status_flags,const ImRect item_rect); CIMGUI_API void igCalcItemSize(ImVec2 *pOut,ImVec2 size,float default_w,float default_h); CIMGUI_API float igCalcWrapWidthForPos(const ImVec2 pos,float wrap_pos_x); CIMGUI_API void igPushMultiItemsWidths(int components,float width_full); @@ -4633,6 +5019,7 @@ CIMGUI_API void igLogRenderedText(const ImVec2* ref_pos,const char* text,const c CIMGUI_API void igLogSetNextTextDecoration(const char* prefix,const char* suffix); CIMGUI_API bool igBeginChildEx(const char* name,ImGuiID id,const ImVec2 size_arg,ImGuiChildFlags child_flags,ImGuiWindowFlags window_flags); CIMGUI_API bool igBeginPopupEx(ImGuiID id,ImGuiWindowFlags extra_window_flags); +CIMGUI_API bool igBeginPopupMenuEx(ImGuiID id,const char* label,ImGuiWindowFlags extra_window_flags); CIMGUI_API void igOpenPopupEx(ImGuiID id,ImGuiPopupFlags popup_flags); CIMGUI_API void igClosePopupToLevel(int remaining,bool restore_focus_to_window_under_popup); CIMGUI_API void igClosePopupsOverWindow(ImGuiWindow* ref_window,bool restore_focus_to_window_under_popup); @@ -4658,12 +5045,13 @@ CIMGUI_API bool igNavMoveRequestButNoResultYet(void); CIMGUI_API void igNavMoveRequestSubmit(ImGuiDir move_dir,ImGuiDir clip_dir,ImGuiNavMoveFlags move_flags,ImGuiScrollFlags scroll_flags); CIMGUI_API void igNavMoveRequestForward(ImGuiDir move_dir,ImGuiDir clip_dir,ImGuiNavMoveFlags move_flags,ImGuiScrollFlags scroll_flags); CIMGUI_API void igNavMoveRequestResolveWithLastItem(ImGuiNavItemData* result); -CIMGUI_API void igNavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result,ImGuiTreeNodeStackData* tree_node_data); +CIMGUI_API void igNavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result,const ImGuiTreeNodeStackData* tree_node_data); CIMGUI_API void igNavMoveRequestCancel(void); CIMGUI_API void igNavMoveRequestApplyResult(void); CIMGUI_API void igNavMoveRequestTryWrapping(ImGuiWindow* window,ImGuiNavMoveFlags move_flags); CIMGUI_API void igNavHighlightActivated(ImGuiID id); CIMGUI_API void igNavClearPreferredPosForAxis(ImGuiAxis axis); +CIMGUI_API void igSetNavCursorVisibleAfterMove(void); CIMGUI_API void igNavUpdateCurrentWindowIsScrollPushableX(void); CIMGUI_API void igSetNavWindow(ImGuiWindow* window); CIMGUI_API void igSetNavID(ImGuiID id,ImGuiNavLayer nav_layer,ImGuiID focus_scope_id,const ImRect rect_rel); @@ -4677,6 +5065,7 @@ CIMGUI_API bool igIsKeyboardKey(ImGuiKey key); CIMGUI_API bool igIsGamepadKey(ImGuiKey key); CIMGUI_API bool igIsMouseKey(ImGuiKey key); CIMGUI_API bool igIsAliasKey(ImGuiKey key); +CIMGUI_API bool igIsLRModKey(ImGuiKey key); CIMGUI_API ImGuiKeyChord igFixupKeyChord(ImGuiKeyChord key_chord); CIMGUI_API ImGuiKey igConvertSingleModFlagToKey(ImGuiKey key); CIMGUI_API ImGuiKeyData* igGetKeyData_ContextPtr(ImGuiContext* ctx,ImGuiKey key); @@ -4789,6 +5178,8 @@ CIMGUI_API float igTableGetHeaderRowHeight(void); CIMGUI_API float igTableGetHeaderAngledMaxLabelWidth(void); CIMGUI_API void igTablePushBackgroundChannel(void); CIMGUI_API void igTablePopBackgroundChannel(void); +CIMGUI_API void igTablePushColumnChannel(int column_n); +CIMGUI_API void igTablePopColumnChannel(void); CIMGUI_API void igTableAngledHeadersRowEx(ImGuiID row_id,float angle,float max_label_width,const ImGuiTableHeaderData* data,int data_count); CIMGUI_API ImGuiTable* igGetCurrentTable(void); CIMGUI_API ImGuiTable* igTableFindByID(ImGuiID id); @@ -4817,6 +5208,7 @@ CIMGUI_API void igTableEndCell(ImGuiTable* table); CIMGUI_API void igTableGetCellBgRect(ImRect *pOut,const ImGuiTable* table,int column_n); CIMGUI_API const char* igTableGetColumnName_TablePtr(const ImGuiTable* table,int column_n); CIMGUI_API ImGuiID igTableGetColumnResizeID(ImGuiTable* table,int column_n,int instance_no); +CIMGUI_API float igTableCalcMaxColumnWidth(const ImGuiTable* table,int column_n); CIMGUI_API void igTableSetColumnWidthAutoSingle(ImGuiTable* table,int column_n); CIMGUI_API void igTableSetColumnWidthAutoAll(ImGuiTable* table); CIMGUI_API void igTableRemove(ImGuiTable* table); @@ -4841,11 +5233,13 @@ CIMGUI_API const char* igTabBarGetTabName(ImGuiTabBar* tab_bar,ImGuiTabItem* tab CIMGUI_API void igTabBarAddTab(ImGuiTabBar* tab_bar,ImGuiTabItemFlags tab_flags,ImGuiWindow* window); CIMGUI_API void igTabBarRemoveTab(ImGuiTabBar* tab_bar,ImGuiID tab_id); CIMGUI_API void igTabBarCloseTab(ImGuiTabBar* tab_bar,ImGuiTabItem* tab); -CIMGUI_API void igTabBarQueueFocus(ImGuiTabBar* tab_bar,ImGuiTabItem* tab); +CIMGUI_API void igTabBarQueueFocus_TabItemPtr(ImGuiTabBar* tab_bar,ImGuiTabItem* tab); +CIMGUI_API void igTabBarQueueFocus_Str(ImGuiTabBar* tab_bar,const char* tab_name); CIMGUI_API void igTabBarQueueReorder(ImGuiTabBar* tab_bar,ImGuiTabItem* tab,int offset); CIMGUI_API void igTabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar,ImGuiTabItem* tab,ImVec2 mouse_pos); CIMGUI_API bool igTabBarProcessReorder(ImGuiTabBar* tab_bar); CIMGUI_API bool igTabItemEx(ImGuiTabBar* tab_bar,const char* label,bool* p_open,ImGuiTabItemFlags flags,ImGuiWindow* docked_window); +CIMGUI_API void igTabItemSpacing(const char* str_id,ImGuiTabItemFlags flags,float width); CIMGUI_API void igTabItemCalcSize_Str(ImVec2 *pOut,const char* label,bool has_close_button_or_unsaved_marker); CIMGUI_API void igTabItemCalcSize_WindowPtr(ImVec2 *pOut,ImGuiWindow* window); CIMGUI_API void igTabItemBackground(ImDrawList* draw_list,const ImRect bb,ImGuiTabItemFlags flags,ImU32 col); @@ -4854,10 +5248,11 @@ CIMGUI_API void igRenderText(ImVec2 pos,const char* text,const char* text_end,bo CIMGUI_API void igRenderTextWrapped(ImVec2 pos,const char* text,const char* text_end,float wrap_width); CIMGUI_API void igRenderTextClipped(const ImVec2 pos_min,const ImVec2 pos_max,const char* text,const char* text_end,const ImVec2* text_size_if_known,const ImVec2 align,const ImRect* clip_rect); CIMGUI_API void igRenderTextClippedEx(ImDrawList* draw_list,const ImVec2 pos_min,const ImVec2 pos_max,const char* text,const char* text_end,const ImVec2* text_size_if_known,const ImVec2 align,const ImRect* clip_rect); -CIMGUI_API void igRenderTextEllipsis(ImDrawList* draw_list,const ImVec2 pos_min,const ImVec2 pos_max,float clip_max_x,float ellipsis_max_x,const char* text,const char* text_end,const ImVec2* text_size_if_known); -CIMGUI_API void igRenderFrame(ImVec2 p_min,ImVec2 p_max,ImU32 fill_col,bool border,float rounding); +CIMGUI_API void igRenderTextEllipsis(ImDrawList* draw_list,const ImVec2 pos_min,const ImVec2 pos_max,float ellipsis_max_x,const char* text,const char* text_end,const ImVec2* text_size_if_known); +CIMGUI_API void igRenderFrame(ImVec2 p_min,ImVec2 p_max,ImU32 fill_col,bool borders,float rounding); CIMGUI_API void igRenderFrameBorder(ImVec2 p_min,ImVec2 p_max,float rounding); CIMGUI_API void igRenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list,ImVec2 p_min,ImVec2 p_max,ImU32 fill_col,float grid_step,ImVec2 grid_off,float rounding,ImDrawFlags flags); +CIMGUI_API void igRenderNavCursor(const ImRect bb,ImGuiID id,ImGuiNavRenderCursorFlags flags); CIMGUI_API const char* igFindRenderedTextEnd(const char* text,const char* text_end); CIMGUI_API void igRenderMouseCursor(ImVec2 pos,float scale,ImGuiMouseCursor mouse_cursor,ImU32 col_fill,ImU32 col_border,ImU32 col_shadow); CIMGUI_API void igRenderArrow(ImDrawList* draw_list,ImVec2 pos,ImU32 col,ImGuiDir dir,float scale); @@ -4869,9 +5264,14 @@ CIMGUI_API void igRenderRectFilledRangeH(ImDrawList* draw_list,const ImRect rect CIMGUI_API void igRenderRectFilledWithHole(ImDrawList* draw_list,const ImRect outer,const ImRect inner,ImU32 col,float rounding); CIMGUI_API ImDrawFlags igCalcRoundingFlagsForRectInRect(const ImRect r_in,const ImRect r_outer,float threshold); CIMGUI_API void igTextEx(const char* text,const char* text_end,ImGuiTextFlags flags); +CIMGUI_API void igTextAligned(float align_x,float size_x,const char* fmt,...); +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igTextAligned0(float align_x,float size_x,const char* fmt); +#endif +CIMGUI_API void igTextAlignedV(float align_x,float size_x,const char* fmt,va_list args); CIMGUI_API bool igButtonEx(const char* label,const ImVec2 size_arg,ImGuiButtonFlags flags); CIMGUI_API bool igArrowButtonEx(const char* str_id,ImGuiDir dir,ImVec2 size_arg,ImGuiButtonFlags flags); -CIMGUI_API bool igImageButtonEx(ImGuiID id,ImTextureID texture_id,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1,const ImVec4 bg_col,const ImVec4 tint_col,ImGuiButtonFlags flags); +CIMGUI_API bool igImageButtonEx(ImGuiID id,ImTextureRef tex_ref,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1,const ImVec4 bg_col,const ImVec4 tint_col,ImGuiButtonFlags flags); CIMGUI_API void igSeparatorEx(ImGuiSeparatorFlags flags,float thickness); CIMGUI_API void igSeparatorTextEx(ImGuiID id,const char* label,const char* label_end,float extra_width); CIMGUI_API bool igCheckboxFlags_S64Ptr(const char* label,ImS64* flags,ImS64 flags_value); @@ -4879,7 +5279,7 @@ CIMGUI_API bool igCheckboxFlags_U64Ptr(const char* label,ImU64* flags,ImU64 flag CIMGUI_API bool igCloseButton(ImGuiID id,const ImVec2 pos); CIMGUI_API bool igCollapseButton(ImGuiID id,const ImVec2 pos,ImGuiDockNode* dock_node); CIMGUI_API void igScrollbar(ImGuiAxis axis); -CIMGUI_API bool igScrollbarEx(const ImRect bb,ImGuiID id,ImGuiAxis axis,ImS64* p_scroll_v,ImS64 avail_v,ImS64 contents_v,ImDrawFlags flags); +CIMGUI_API bool igScrollbarEx(const ImRect bb,ImGuiID id,ImGuiAxis axis,ImS64* p_scroll_v,ImS64 avail_v,ImS64 contents_v,ImDrawFlags draw_rounding_flags); CIMGUI_API void igGetWindowScrollbarRect(ImRect *pOut,ImGuiWindow* window,ImGuiAxis axis); CIMGUI_API ImGuiID igGetWindowScrollbarID(ImGuiWindow* window,ImGuiAxis axis); CIMGUI_API ImGuiID igGetWindowResizeCornerID(ImGuiWindow* window,int n); @@ -4889,6 +5289,8 @@ CIMGUI_API bool igDragBehavior(ImGuiID id,ImGuiDataType data_type,void* p_v,floa CIMGUI_API bool igSliderBehavior(const ImRect bb,ImGuiID id,ImGuiDataType data_type,void* p_v,const void* p_min,const void* p_max,const char* format,ImGuiSliderFlags flags,ImRect* out_grab_bb); CIMGUI_API bool igSplitterBehavior(const ImRect bb,ImGuiID id,ImGuiAxis axis,float* size1,float* size2,float min_size1,float min_size2,float hover_extend,float hover_visibility_delay,ImU32 bg_col); CIMGUI_API bool igTreeNodeBehavior(ImGuiID id,ImGuiTreeNodeFlags flags,const char* label,const char* label_end); +CIMGUI_API void igTreeNodeDrawLineToChildNode(const ImVec2 target_pos); +CIMGUI_API void igTreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data); CIMGUI_API void igTreePushOverrideID(ImGuiID id); CIMGUI_API bool igTreeNodeGetOpen(ImGuiID storage_id); CIMGUI_API void igTreeNodeSetOpen(ImGuiID storage_id,bool open); @@ -4899,6 +5301,7 @@ CIMGUI_API void igDataTypeApplyOp(ImGuiDataType data_type,int op,void* output,co CIMGUI_API bool igDataTypeApplyFromText(const char* buf,ImGuiDataType data_type,void* p_data,const char* format,void* p_data_when_empty); CIMGUI_API int igDataTypeCompare(ImGuiDataType data_type,const void* arg_1,const void* arg_2); CIMGUI_API bool igDataTypeClamp(ImGuiDataType data_type,void* p_data,const void* p_min,const void* p_max); +CIMGUI_API bool igDataTypeIsZero(ImGuiDataType data_type,const void* p_data); CIMGUI_API bool igInputTextEx(const char* label,const char* hint,char* buf,int buf_size,const ImVec2 size_arg,ImGuiInputTextFlags flags,ImGuiInputTextCallback callback,void* user_data); CIMGUI_API void igInputTextDeactivateHook(ImGuiID id); CIMGUI_API bool igTempInputText(const ImRect bb,ImGuiID id,const char* label,char* buf,int buf_size,ImGuiInputTextFlags flags); @@ -4906,6 +5309,7 @@ CIMGUI_API bool igTempInputScalar(const ImRect bb,ImGuiID id,const char* label,I CIMGUI_API bool igTempInputIsActive(ImGuiID id); CIMGUI_API ImGuiInputTextState* igGetInputTextState(ImGuiID id); CIMGUI_API void igSetNextItemRefVal(ImGuiDataType data_type,void* p_data); +CIMGUI_API bool igIsItemActiveAsInputText(void); CIMGUI_API void igColorTooltip(const char* text,const float* col,ImGuiColorEditFlags flags); CIMGUI_API void igColorEditOptionsPopup(const float* col,ImGuiColorEditFlags flags); CIMGUI_API void igColorPickerOptionsPopup(const float* ref_col,ImGuiColorEditFlags flags); @@ -4916,8 +5320,15 @@ CIMGUI_API void igShadeVertsTransformPos(ImDrawList* draw_list,int vert_start_id CIMGUI_API void igGcCompactTransientMiscBuffers(void); CIMGUI_API void igGcCompactTransientWindowBuffers(ImGuiWindow* window); CIMGUI_API void igGcAwakeTransientWindowBuffers(ImGuiWindow* window); -CIMGUI_API void igDebugAllocHook(ImGuiDebugAllocInfo* info,int frame_count,void* ptr,size_t size); +CIMGUI_API bool igErrorLog(const char* msg); +CIMGUI_API void igErrorRecoveryStoreState(ImGuiErrorRecoveryState* state_out); +CIMGUI_API void igErrorRecoveryTryToRecoverState(const ImGuiErrorRecoveryState* state_in); +CIMGUI_API void igErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryState* state_in); CIMGUI_API void igErrorCheckUsingSetCursorPosToExtendParentBoundaries(void); +CIMGUI_API void igErrorCheckEndFrameFinalizeErrorTooltip(void); +CIMGUI_API bool igBeginErrorTooltip(void); +CIMGUI_API void igEndErrorTooltip(void); +CIMGUI_API void igDebugAllocHook(ImGuiDebugAllocInfo* info,int frame_count,void* ptr,size_t size); CIMGUI_API void igDebugDrawCursorPos(ImU32 col); CIMGUI_API void igDebugDrawLineExtents(ImU32 col); CIMGUI_API void igDebugDrawItemRect(ImU32 col); @@ -4935,7 +5346,9 @@ CIMGUI_API void igDebugNodeDockNode(ImGuiDockNode* node,const char* label); CIMGUI_API void igDebugNodeDrawList(ImGuiWindow* window,ImGuiViewportP* viewport,const ImDrawList* draw_list,const char* label); CIMGUI_API void igDebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list,const ImDrawList* draw_list,const ImDrawCmd* draw_cmd,bool show_mesh,bool show_aabb); CIMGUI_API void igDebugNodeFont(ImFont* font); +CIMGUI_API void igDebugNodeFontGlyphesForSrcMask(ImFont* font,ImFontBaked* baked,int src_mask); CIMGUI_API void igDebugNodeFontGlyph(ImFont* font,const ImFontGlyph* glyph); +CIMGUI_API void igDebugNodeTexture(ImTextureData* tex,int int_id,const ImFontAtlasRect* highlight_rect); CIMGUI_API void igDebugNodeStorage(ImGuiStorage* storage,const char* label); CIMGUI_API void igDebugNodeTabBar(ImGuiTabBar* tab_bar,const char* label); CIMGUI_API void igDebugNodeTable(ImGuiTable* table); @@ -4951,23 +5364,76 @@ CIMGUI_API void igDebugNodeViewport(ImGuiViewportP* viewport); CIMGUI_API void igDebugNodePlatformMonitor(ImGuiPlatformMonitor* monitor,const char* label,int idx); CIMGUI_API void igDebugRenderKeyboardPreview(ImDrawList* draw_list); CIMGUI_API void igDebugRenderViewportThumbnail(ImDrawList* draw_list,ImGuiViewportP* viewport,const ImRect bb); -CIMGUI_API const ImFontBuilderIO* igImFontAtlasGetBuilderForStbTruetype(void); -CIMGUI_API void igImFontAtlasUpdateConfigDataPointers(ImFontAtlas* atlas); +CIMGUI_API ImFontLoader* ImFontLoader_ImFontLoader(void); +CIMGUI_API void ImFontLoader_destroy(ImFontLoader* self); +CIMGUI_API const ImFontLoader* igImFontAtlasGetFontLoaderForStbTruetype(void); +CIMGUI_API int igImFontAtlasRectId_GetIndex(ImFontAtlasRectId id); +CIMGUI_API int igImFontAtlasRectId_GetGeneration(ImFontAtlasRectId id); +CIMGUI_API ImFontAtlasRectId igImFontAtlasRectId_Make(int index_idx,int gen_idx); +CIMGUI_API ImFontAtlasBuilder* ImFontAtlasBuilder_ImFontAtlasBuilder(void); +CIMGUI_API void ImFontAtlasBuilder_destroy(ImFontAtlasBuilder* self); CIMGUI_API void igImFontAtlasBuildInit(ImFontAtlas* atlas); -CIMGUI_API void igImFontAtlasBuildSetupFont(ImFontAtlas* atlas,ImFont* font,ImFontConfig* font_config,float ascent,float descent); -CIMGUI_API void igImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas,void* stbrp_context_opaque); -CIMGUI_API void igImFontAtlasBuildFinish(ImFontAtlas* atlas); -CIMGUI_API void igImFontAtlasBuildRender8bppRectFromString(ImFontAtlas* atlas,int x,int y,int w,int h,const char* in_str,char in_marker_char,unsigned char in_marker_pixel_value); -CIMGUI_API void igImFontAtlasBuildRender32bppRectFromString(ImFontAtlas* atlas,int x,int y,int w,int h,const char* in_str,char in_marker_char,unsigned int in_marker_pixel_value); -CIMGUI_API void igImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256],float in_multiply_factor); -CIMGUI_API void igImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256],unsigned char* pixels,int x,int y,int w,int h,int stride); +CIMGUI_API void igImFontAtlasBuildDestroy(ImFontAtlas* atlas); +CIMGUI_API void igImFontAtlasBuildMain(ImFontAtlas* atlas); +CIMGUI_API void igImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas,const ImFontLoader* font_loader); +CIMGUI_API void igImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas); +CIMGUI_API void igImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas,int x,int y,int w,int h,const char* in_str,char in_marker_char); +CIMGUI_API void igImFontAtlasBuildClear(ImFontAtlas* atlas); +CIMGUI_API ImTextureData* igImFontAtlasTextureAdd(ImFontAtlas* atlas,int w,int h); +CIMGUI_API void igImFontAtlasTextureMakeSpace(ImFontAtlas* atlas); +CIMGUI_API void igImFontAtlasTextureRepack(ImFontAtlas* atlas,int w,int h); +CIMGUI_API void igImFontAtlasTextureGrow(ImFontAtlas* atlas,int old_w,int old_h); +CIMGUI_API void igImFontAtlasTextureCompact(ImFontAtlas* atlas); +CIMGUI_API void igImFontAtlasTextureGetSizeEstimate(ImVec2i *pOut,ImFontAtlas* atlas); +CIMGUI_API void igImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas,ImFont* font,ImFontConfig* src); +CIMGUI_API void igImFontAtlasBuildLegacyPreloadAllGlyphRanges(ImFontAtlas* atlas); +CIMGUI_API void igImFontAtlasBuildGetOversampleFactors(ImFontConfig* src,ImFontBaked* baked,int* out_oversample_h,int* out_oversample_v); +CIMGUI_API void igImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas,int unused_frames); +CIMGUI_API bool igImFontAtlasFontSourceInit(ImFontAtlas* atlas,ImFontConfig* src); +CIMGUI_API void igImFontAtlasFontSourceAddToFont(ImFontAtlas* atlas,ImFont* font,ImFontConfig* src); +CIMGUI_API void igImFontAtlasFontDestroySourceData(ImFontAtlas* atlas,ImFontConfig* src); +CIMGUI_API bool igImFontAtlasFontInitOutput(ImFontAtlas* atlas,ImFont* font); +CIMGUI_API void igImFontAtlasFontDestroyOutput(ImFontAtlas* atlas,ImFont* font); +CIMGUI_API void igImFontAtlasFontDiscardBakes(ImFontAtlas* atlas,ImFont* font,int unused_frames); +CIMGUI_API ImGuiID igImFontAtlasBakedGetId(ImGuiID font_id,float baked_size,float rasterizer_density); +CIMGUI_API ImFontBaked* igImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas,ImFont* font,float font_size,float font_rasterizer_density); +CIMGUI_API ImFontBaked* igImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas,ImFont* font,float font_size,float font_rasterizer_density); +CIMGUI_API ImFontBaked* igImFontAtlasBakedAdd(ImFontAtlas* atlas,ImFont* font,float font_size,float font_rasterizer_density,ImGuiID baked_id); +CIMGUI_API void igImFontAtlasBakedDiscard(ImFontAtlas* atlas,ImFont* font,ImFontBaked* baked); +CIMGUI_API ImFontGlyph* igImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas,ImFontBaked* baked,ImFontConfig* src,const ImFontGlyph* in_glyph); +CIMGUI_API void igImFontAtlasBakedDiscardFontGlyph(ImFontAtlas* atlas,ImFont* font,ImFontBaked* baked,ImFontGlyph* glyph); +CIMGUI_API void igImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas,ImFontBaked* baked,ImFontConfig* src,ImFontGlyph* glyph,ImTextureRect* r,const unsigned char* src_pixels,ImTextureFormat src_fmt,int src_pitch); +CIMGUI_API void igImFontAtlasPackInit(ImFontAtlas* atlas); +CIMGUI_API ImFontAtlasRectId igImFontAtlasPackAddRect(ImFontAtlas* atlas,int w,int h,ImFontAtlasRectEntry* overwrite_entry); +CIMGUI_API ImTextureRect* igImFontAtlasPackGetRect(ImFontAtlas* atlas,ImFontAtlasRectId id); +CIMGUI_API ImTextureRect* igImFontAtlasPackGetRectSafe(ImFontAtlas* atlas,ImFontAtlasRectId id); +CIMGUI_API void igImFontAtlasPackDiscardRect(ImFontAtlas* atlas,ImFontAtlasRectId id); +CIMGUI_API void igImFontAtlasUpdateNewFrame(ImFontAtlas* atlas,int frame_count,bool renderer_has_textures); +CIMGUI_API void igImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas,ImDrawListSharedData* data); +CIMGUI_API void igImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas,ImDrawListSharedData* data); +CIMGUI_API void igImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas,ImTextureRef old_tex,ImTextureRef new_tex); +CIMGUI_API void igImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas); +CIMGUI_API void igImFontAtlasTextureBlockConvert(const unsigned char* src_pixels,ImTextureFormat src_fmt,int src_pitch,unsigned char* dst_pixels,ImTextureFormat dst_fmt,int dst_pitch,int w,int h); +CIMGUI_API void igImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data); +CIMGUI_API void igImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data,float multiply_factor); +CIMGUI_API void igImFontAtlasTextureBlockFill(ImTextureData* dst_tex,int dst_x,int dst_y,int w,int h,ImU32 col); +CIMGUI_API void igImFontAtlasTextureBlockCopy(ImTextureData* src_tex,int src_x,int src_y,ImTextureData* dst_tex,int dst_x,int dst_y,int w,int h); +CIMGUI_API void igImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas,ImTextureData* tex,int x,int y,int w,int h); +CIMGUI_API int igImTextureDataGetFormatBytesPerPixel(ImTextureFormat format); +CIMGUI_API const char* igImTextureDataGetStatusName(ImTextureStatus status); +CIMGUI_API const char* igImTextureDataGetFormatName(ImTextureFormat format); +CIMGUI_API void igImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas); +CIMGUI_API bool igImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas,ImGuiMouseCursor cursor_type,ImVec2* out_offset,ImVec2* out_size,ImVec2 out_uv_border[2],ImVec2 out_uv_fill[2]); +#ifdef IMGUI_ENABLE_FREETYPE +CIMGUI_API const ImFontLoader* ImGuiFreeType_GetFontLoader(void); +CIMGUI_API void ImGuiFreeType_SetAllocatorFunctions(void*(*alloc_func)(size_t sz,void* user_data),void(*free_func)(void* ptr,void* user_data),void* user_data); +CIMGUI_API bool ImGuiFreeType_DebugEditFontLoaderFlags(ImGuiFreeTypeLoaderFlags* p_font_loader_flags); +#endif /////////////////////////hand written functions -//no LogTextV -CIMGUI_API void igLogText(CONST char *fmt, ...); //no appendfV -CIMGUI_API void ImGuiTextBuffer_appendf(struct ImGuiTextBuffer *buffer, const char *fmt, ...); +CIMGUI_API void ImGuiTextBuffer_appendf(ImGuiTextBuffer *self, const char *fmt, ...); //for getting FLT_MAX in bindings CIMGUI_API float igGET_FLT_MAX(void); //for getting FLT_MIN in bindings diff --git a/lib/third_party/imgui/cimgui/source/cimgui.cpp b/lib/third_party/imgui/cimgui/source/cimgui.cpp index ad27917e7..9a27d0d88 100644 --- a/lib/third_party/imgui/cimgui/source/cimgui.cpp +++ b/lib/third_party/imgui/cimgui/source/cimgui.cpp @@ -1,25 +1,13 @@ //This file is automatically generated by generator.lua from https://github.com/cimgui/cimgui -//based on imgui.h file version "1.91.0" 19100 from Dear ImGui https://github.com/ocornut/imgui +//based on imgui.h file version "1.92.0" 19200 from Dear ImGui https://github.com/ocornut/imgui //with imgui_internal.h api +//with imgui_freetype.h api //docking branch -#ifdef IMGUI_ENABLE_FREETYPE -#ifndef CIMGUI_FREETYPE -#error "IMGUI_FREETYPE should be defined for Freetype linking" -#endif -#else -#ifdef CIMGUI_FREETYPE -#error "IMGUI_FREETYPE should not be defined without freetype generated cimgui" -#endif -#endif -#include "imgui.h" -#ifdef IMGUI_ENABLE_FREETYPE -#include "misc/freetype/imgui_freetype.h" -#endif -#include "imgui_internal.h" + +#include +#include #include "cimgui.h" - - CIMGUI_API ImVec2* ImVec2_ImVec2_Nil(void) { return IM_NEW(ImVec2)(); @@ -44,6 +32,22 @@ CIMGUI_API ImVec4* ImVec4_ImVec4_Float(float _x,float _y,float _z,float _w) { return IM_NEW(ImVec4)(_x,_y,_z,_w); } +CIMGUI_API ImTextureRef* ImTextureRef_ImTextureRef_Nil(void) +{ + return IM_NEW(ImTextureRef)(); +} +CIMGUI_API void ImTextureRef_destroy(ImTextureRef* self) +{ + IM_DELETE(self); +} +CIMGUI_API ImTextureRef* ImTextureRef_ImTextureRef_TextureID(ImTextureID tex_id) +{ + return IM_NEW(ImTextureRef)(tex_id); +} +CIMGUI_API ImTextureID ImTextureRef_GetTexID(ImTextureRef* self) +{ + return self->GetTexID(); +} CIMGUI_API ImGuiContext* igCreateContext(ImFontAtlas* shared_font_atlas) { return ImGui::CreateContext(shared_font_atlas); @@ -60,10 +64,14 @@ CIMGUI_API void igSetCurrentContext(ImGuiContext* ctx) { return ImGui::SetCurrentContext(ctx); } -CIMGUI_API ImGuiIO* igGetIO() +CIMGUI_API ImGuiIO* igGetIO_Nil() { return &ImGui::GetIO(); } +CIMGUI_API ImGuiPlatformIO* igGetPlatformIO_Nil() +{ + return &ImGui::GetPlatformIO(); +} CIMGUI_API ImGuiStyle* igGetStyle() { return &ImGui::GetStyle(); @@ -252,10 +260,6 @@ CIMGUI_API void igSetWindowFocus_Nil() { return ImGui::SetWindowFocus(); } -CIMGUI_API void igSetWindowFontScale(float scale) -{ - return ImGui::SetWindowFontScale(scale); -} CIMGUI_API void igSetWindowPos_Str(const char* name,const ImVec2 pos,ImGuiCond cond) { return ImGui::SetWindowPos(name,pos,cond); @@ -312,14 +316,26 @@ CIMGUI_API void igSetScrollFromPosY_Float(float local_y,float center_y_ratio) { return ImGui::SetScrollFromPosY(local_y,center_y_ratio); } -CIMGUI_API void igPushFont(ImFont* font) +CIMGUI_API void igPushFont(ImFont* font,float font_size_base_unscaled) { - return ImGui::PushFont(font); + return ImGui::PushFont(font,font_size_base_unscaled); } CIMGUI_API void igPopFont() { return ImGui::PopFont(); } +CIMGUI_API ImFont* igGetFont() +{ + return ImGui::GetFont(); +} +CIMGUI_API float igGetFontSize() +{ + return ImGui::GetFontSize(); +} +CIMGUI_API ImFontBaked* igGetFontBaked() +{ + return ImGui::GetFontBaked(); +} CIMGUI_API void igPushStyleColor_U32(ImGuiCol idx,ImU32 col) { return ImGui::PushStyleColor(idx,col); @@ -340,6 +356,14 @@ CIMGUI_API void igPushStyleVar_Vec2(ImGuiStyleVar idx,const ImVec2 val) { return ImGui::PushStyleVar(idx,val); } +CIMGUI_API void igPushStyleVarX(ImGuiStyleVar idx,float val_x) +{ + return ImGui::PushStyleVarX(idx,val_x); +} +CIMGUI_API void igPushStyleVarY(ImGuiStyleVar idx,float val_y) +{ + return ImGui::PushStyleVarY(idx,val_y); +} CIMGUI_API void igPopStyleVar(int count) { return ImGui::PopStyleVar(count); @@ -376,14 +400,6 @@ CIMGUI_API void igPopTextWrapPos() { return ImGui::PopTextWrapPos(); } -CIMGUI_API ImFont* igGetFont() -{ - return ImGui::GetFont(); -} -CIMGUI_API float igGetFontSize() -{ - return ImGui::GetFontSize(); -} CIMGUI_API void igGetFontTexUvWhitePixel(ImVec2 *pOut) { *pOut = ImGui::GetFontTexUvWhitePixel(); @@ -547,6 +563,12 @@ CIMGUI_API void igText(const char* fmt,...) ImGui::TextV(fmt,args); va_end(args); } +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igText0(const char* fmt) +{ + return igText(fmt); +} +#endif CIMGUI_API void igTextV(const char* fmt,va_list args) { return ImGui::TextV(fmt,args); @@ -558,6 +580,12 @@ CIMGUI_API void igTextColored(const ImVec4 col,const char* fmt,...) ImGui::TextColoredV(col,fmt,args); va_end(args); } +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igTextColored0(const ImVec4 col,const char* fmt) +{ + return igTextColored(col,fmt); +} +#endif CIMGUI_API void igTextColoredV(const ImVec4 col,const char* fmt,va_list args) { return ImGui::TextColoredV(col,fmt,args); @@ -569,6 +597,12 @@ CIMGUI_API void igTextDisabled(const char* fmt,...) ImGui::TextDisabledV(fmt,args); va_end(args); } +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igTextDisabled0(const char* fmt) +{ + return igTextDisabled(fmt); +} +#endif CIMGUI_API void igTextDisabledV(const char* fmt,va_list args) { return ImGui::TextDisabledV(fmt,args); @@ -580,6 +614,12 @@ CIMGUI_API void igTextWrapped(const char* fmt,...) ImGui::TextWrappedV(fmt,args); va_end(args); } +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igTextWrapped0(const char* fmt) +{ + return igTextWrapped(fmt); +} +#endif CIMGUI_API void igTextWrappedV(const char* fmt,va_list args) { return ImGui::TextWrappedV(fmt,args); @@ -591,6 +631,12 @@ CIMGUI_API void igLabelText(const char* label,const char* fmt,...) ImGui::LabelTextV(label,fmt,args); va_end(args); } +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igLabelText0(const char* label,const char* fmt) +{ + return igLabelText(label,fmt); +} +#endif CIMGUI_API void igLabelTextV(const char* label,const char* fmt,va_list args) { return ImGui::LabelTextV(label,fmt,args); @@ -602,6 +648,12 @@ CIMGUI_API void igBulletText(const char* fmt,...) ImGui::BulletTextV(fmt,args); va_end(args); } +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igBulletText0(const char* fmt) +{ + return igBulletText(fmt); +} +#endif CIMGUI_API void igBulletTextV(const char* fmt,va_list args) { return ImGui::BulletTextV(fmt,args); @@ -658,17 +710,21 @@ CIMGUI_API bool igTextLink(const char* label) { return ImGui::TextLink(label); } -CIMGUI_API void igTextLinkOpenURL(const char* label,const char* url) +CIMGUI_API bool igTextLinkOpenURL(const char* label,const char* url) { return ImGui::TextLinkOpenURL(label,url); } -CIMGUI_API void igImage(ImTextureID user_texture_id,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1) +CIMGUI_API void igImage(ImTextureRef tex_ref,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1) { - return ImGui::Image(user_texture_id,image_size,uv0,uv1); + return ImGui::Image(tex_ref,image_size,uv0,uv1); } -CIMGUI_API bool igImageButton(const char* str_id,ImTextureID user_texture_id,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1,const ImVec4 bg_col,const ImVec4 tint_col) +CIMGUI_API void igImageWithBg(ImTextureRef tex_ref,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1,const ImVec4 bg_col,const ImVec4 tint_col) { - return ImGui::ImageButton(str_id,user_texture_id,image_size,uv0,uv1,bg_col,tint_col); + return ImGui::ImageWithBg(tex_ref,image_size,uv0,uv1,bg_col,tint_col); +} +CIMGUI_API bool igImageButton(const char* str_id,ImTextureRef tex_ref,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1,const ImVec4 bg_col,const ImVec4 tint_col) +{ + return ImGui::ImageButton(str_id,tex_ref,image_size,uv0,uv1,bg_col,tint_col); } CIMGUI_API bool igBeginCombo(const char* label,const char* preview_value,ImGuiComboFlags flags) { @@ -886,6 +942,12 @@ CIMGUI_API bool igTreeNode_StrStr(const char* str_id,const char* fmt,...) va_end(args); return ret; } +#ifdef CIMGUI_VARGS0 +CIMGUI_API bool igTreeNode_StrStr0(const char* str_id,const char* fmt) +{ + return igTreeNode_StrStr(str_id,fmt); +} +#endif CIMGUI_API bool igTreeNode_Ptr(const void* ptr_id,const char* fmt,...) { va_list args; @@ -894,6 +956,12 @@ CIMGUI_API bool igTreeNode_Ptr(const void* ptr_id,const char* fmt,...) va_end(args); return ret; } +#ifdef CIMGUI_VARGS0 +CIMGUI_API bool igTreeNode_Ptr0(const void* ptr_id,const char* fmt) +{ + return igTreeNode_Ptr(ptr_id,fmt); +} +#endif CIMGUI_API bool igTreeNodeV_Str(const char* str_id,const char* fmt,va_list args) { return ImGui::TreeNodeV(str_id,fmt,args); @@ -914,6 +982,12 @@ CIMGUI_API bool igTreeNodeEx_StrStr(const char* str_id,ImGuiTreeNodeFlags flags, va_end(args); return ret; } +#ifdef CIMGUI_VARGS0 +CIMGUI_API bool igTreeNodeEx_StrStr0(const char* str_id,ImGuiTreeNodeFlags flags,const char* fmt) +{ + return igTreeNodeEx_StrStr(str_id,flags,fmt); +} +#endif CIMGUI_API bool igTreeNodeEx_Ptr(const void* ptr_id,ImGuiTreeNodeFlags flags,const char* fmt,...) { va_list args; @@ -922,6 +996,12 @@ CIMGUI_API bool igTreeNodeEx_Ptr(const void* ptr_id,ImGuiTreeNodeFlags flags,con va_end(args); return ret; } +#ifdef CIMGUI_VARGS0 +CIMGUI_API bool igTreeNodeEx_Ptr0(const void* ptr_id,ImGuiTreeNodeFlags flags,const char* fmt) +{ + return igTreeNodeEx_Ptr(ptr_id,flags,fmt); +} +#endif CIMGUI_API bool igTreeNodeExV_Str(const char* str_id,ImGuiTreeNodeFlags flags,const char* fmt,va_list args) { return ImGui::TreeNodeExV(str_id,flags,fmt,args); @@ -1081,6 +1161,12 @@ CIMGUI_API void igSetTooltip(const char* fmt,...) ImGui::SetTooltipV(fmt,args); va_end(args); } +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igSetTooltip0(const char* fmt) +{ + return igSetTooltip(fmt); +} +#endif CIMGUI_API void igSetTooltipV(const char* fmt,va_list args) { return ImGui::SetTooltipV(fmt,args); @@ -1096,6 +1182,12 @@ CIMGUI_API void igSetItemTooltip(const char* fmt,...) ImGui::SetItemTooltipV(fmt,args); va_end(args); } +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igSetItemTooltip0(const char* fmt) +{ + return igSetItemTooltip(fmt); +} +#endif CIMGUI_API void igSetItemTooltipV(const char* fmt,va_list args) { return ImGui::SetItemTooltipV(fmt,args); @@ -1220,9 +1312,9 @@ CIMGUI_API void igTableSetBgColor(ImGuiTableBgTarget target,ImU32 color,int colu { return ImGui::TableSetBgColor(target,color,column_n); } -CIMGUI_API void igColumns(int count,const char* id,bool border) +CIMGUI_API void igColumns(int count,const char* id,bool borders) { - return ImGui::Columns(count,id,border); + return ImGui::Columns(count,id,borders); } CIMGUI_API void igNextColumn() { @@ -1320,6 +1412,19 @@ CIMGUI_API void igLogButtons() { return ImGui::LogButtons(); } +CIMGUI_API void igLogText(const char* fmt,...) +{ + va_list args; + va_start(args, fmt); + ImGui::LogTextV(fmt,args); + va_end(args); +} +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igLogText0(const char* fmt) +{ + return igLogText(fmt); +} +#endif CIMGUI_API void igLogTextV(const char* fmt,va_list args) { return ImGui::LogTextV(fmt,args); @@ -1376,6 +1481,10 @@ CIMGUI_API void igSetKeyboardFocusHere(int offset) { return ImGui::SetKeyboardFocusHere(offset); } +CIMGUI_API void igSetNavCursorVisible(bool visible) +{ + return ImGui::SetNavCursorVisible(visible); +} CIMGUI_API void igSetNextItemAllowOverlap() { return ImGui::SetNextItemAllowOverlap(); @@ -1568,6 +1677,10 @@ CIMGUI_API bool igIsMouseDoubleClicked_Nil(ImGuiMouseButton button) { return ImGui::IsMouseDoubleClicked(button); } +CIMGUI_API bool igIsMouseReleasedWithDelay(ImGuiMouseButton button,float delay) +{ + return ImGui::IsMouseReleasedWithDelay(button,delay); +} CIMGUI_API int igGetMouseClickedCount(ImGuiMouseButton button) { return ImGui::GetMouseClickedCount(button); @@ -1663,6 +1776,12 @@ CIMGUI_API void igDebugLog(const char* fmt,...) ImGui::DebugLogV(fmt,args); va_end(args); } +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igDebugLog0(const char* fmt) +{ + return igDebugLog(fmt); +} +#endif CIMGUI_API void igDebugLogV(const char* fmt,va_list args) { return ImGui::DebugLogV(fmt,args); @@ -1683,10 +1802,6 @@ CIMGUI_API void igMemFree(void* ptr) { return ImGui::MemFree(ptr); } -CIMGUI_API ImGuiPlatformIO* igGetPlatformIO() -{ - return &ImGui::GetPlatformIO(); -} CIMGUI_API void igUpdatePlatformWindows() { return ImGui::UpdatePlatformWindows(); @@ -1951,6 +2066,10 @@ CIMGUI_API void ImGuiTextBuffer_clear(ImGuiTextBuffer* self) { return self->clear(); } +CIMGUI_API void ImGuiTextBuffer_resize(ImGuiTextBuffer* self,int size) +{ + return self->resize(size); +} CIMGUI_API void ImGuiTextBuffer_reserve(ImGuiTextBuffer* self,int capacity) { return self->reserve(capacity); @@ -2215,13 +2334,13 @@ CIMGUI_API void ImDrawList_PopClipRect(ImDrawList* self) { return self->PopClipRect(); } -CIMGUI_API void ImDrawList_PushTextureID(ImDrawList* self,ImTextureID texture_id) +CIMGUI_API void ImDrawList_PushTexture(ImDrawList* self,ImTextureRef tex_ref) { - return self->PushTextureID(texture_id); + return self->PushTexture(tex_ref); } -CIMGUI_API void ImDrawList_PopTextureID(ImDrawList* self) +CIMGUI_API void ImDrawList_PopTexture(ImDrawList* self) { - return self->PopTextureID(); + return self->PopTexture(); } CIMGUI_API void ImDrawList_GetClipRectMin(ImVec2 *pOut,ImDrawList* self) { @@ -2315,17 +2434,17 @@ CIMGUI_API void ImDrawList_AddConcavePolyFilled(ImDrawList* self,const ImVec2* p { return self->AddConcavePolyFilled(points,num_points,col); } -CIMGUI_API void ImDrawList_AddImage(ImDrawList* self,ImTextureID user_texture_id,const ImVec2 p_min,const ImVec2 p_max,const ImVec2 uv_min,const ImVec2 uv_max,ImU32 col) +CIMGUI_API void ImDrawList_AddImage(ImDrawList* self,ImTextureRef tex_ref,const ImVec2 p_min,const ImVec2 p_max,const ImVec2 uv_min,const ImVec2 uv_max,ImU32 col) { - return self->AddImage(user_texture_id,p_min,p_max,uv_min,uv_max,col); + return self->AddImage(tex_ref,p_min,p_max,uv_min,uv_max,col); } -CIMGUI_API void ImDrawList_AddImageQuad(ImDrawList* self,ImTextureID user_texture_id,const ImVec2 p1,const ImVec2 p2,const ImVec2 p3,const ImVec2 p4,const ImVec2 uv1,const ImVec2 uv2,const ImVec2 uv3,const ImVec2 uv4,ImU32 col) +CIMGUI_API void ImDrawList_AddImageQuad(ImDrawList* self,ImTextureRef tex_ref,const ImVec2 p1,const ImVec2 p2,const ImVec2 p3,const ImVec2 p4,const ImVec2 uv1,const ImVec2 uv2,const ImVec2 uv3,const ImVec2 uv4,ImU32 col) { - return self->AddImageQuad(user_texture_id,p1,p2,p3,p4,uv1,uv2,uv3,uv4,col); + return self->AddImageQuad(tex_ref,p1,p2,p3,p4,uv1,uv2,uv3,uv4,col); } -CIMGUI_API void ImDrawList_AddImageRounded(ImDrawList* self,ImTextureID user_texture_id,const ImVec2 p_min,const ImVec2 p_max,const ImVec2 uv_min,const ImVec2 uv_max,ImU32 col,float rounding,ImDrawFlags flags) +CIMGUI_API void ImDrawList_AddImageRounded(ImDrawList* self,ImTextureRef tex_ref,const ImVec2 p_min,const ImVec2 p_max,const ImVec2 uv_min,const ImVec2 uv_max,ImU32 col,float rounding,ImDrawFlags flags) { - return self->AddImageRounded(user_texture_id,p_min,p_max,uv_min,uv_max,col,rounding,flags); + return self->AddImageRounded(tex_ref,p_min,p_max,uv_min,uv_max,col,rounding,flags); } CIMGUI_API void ImDrawList_PathClear(ImDrawList* self) { @@ -2375,9 +2494,9 @@ CIMGUI_API void ImDrawList_PathRect(ImDrawList* self,const ImVec2 rect_min,const { return self->PathRect(rect_min,rect_max,rounding,flags); } -CIMGUI_API void ImDrawList_AddCallback(ImDrawList* self,ImDrawCallback callback,void* callback_data) +CIMGUI_API void ImDrawList_AddCallback(ImDrawList* self,ImDrawCallback callback,void* userdata,size_t userdata_size) { - return self->AddCallback(callback,callback_data); + return self->AddCallback(callback,userdata,userdata_size); } CIMGUI_API void ImDrawList_AddDrawCmd(ImDrawList* self) { @@ -2431,6 +2550,10 @@ CIMGUI_API void ImDrawList_PrimVtx(ImDrawList* self,const ImVec2 pos,const ImVec { return self->PrimVtx(pos,uv,col); } +CIMGUI_API void ImDrawList__SetDrawListSharedData(ImDrawList* self,ImDrawListSharedData* data) +{ + return self->_SetDrawListSharedData(data); +} CIMGUI_API void ImDrawList__ResetForNewFrame(ImDrawList* self) { return self->_ResetForNewFrame(); @@ -2451,14 +2574,18 @@ CIMGUI_API void ImDrawList__OnChangedClipRect(ImDrawList* self) { return self->_OnChangedClipRect(); } -CIMGUI_API void ImDrawList__OnChangedTextureID(ImDrawList* self) +CIMGUI_API void ImDrawList__OnChangedTexture(ImDrawList* self) { - return self->_OnChangedTextureID(); + return self->_OnChangedTexture(); } CIMGUI_API void ImDrawList__OnChangedVtxOffset(ImDrawList* self) { return self->_OnChangedVtxOffset(); } +CIMGUI_API void ImDrawList__SetTexture(ImDrawList* self,ImTextureRef tex_ref) +{ + return self->_SetTexture(tex_ref); +} CIMGUI_API int ImDrawList__CalcCircleAutoSegmentCount(ImDrawList* self,float radius) { return self->_CalcCircleAutoSegmentCount(radius); @@ -2495,6 +2622,54 @@ CIMGUI_API void ImDrawData_ScaleClipRects(ImDrawData* self,const ImVec2 fb_scale { return self->ScaleClipRects(fb_scale); } +CIMGUI_API ImTextureData* ImTextureData_ImTextureData(void) +{ + return IM_NEW(ImTextureData)(); +} +CIMGUI_API void ImTextureData_destroy(ImTextureData* self) +{ + IM_DELETE(self); +} +CIMGUI_API void ImTextureData_Create(ImTextureData* self,ImTextureFormat format,int w,int h) +{ + return self->Create(format,w,h); +} +CIMGUI_API void ImTextureData_DestroyPixels(ImTextureData* self) +{ + return self->DestroyPixels(); +} +CIMGUI_API void* ImTextureData_GetPixels(ImTextureData* self) +{ + return self->GetPixels(); +} +CIMGUI_API void* ImTextureData_GetPixelsAt(ImTextureData* self,int x,int y) +{ + return self->GetPixelsAt(x,y); +} +CIMGUI_API int ImTextureData_GetSizeInBytes(ImTextureData* self) +{ + return self->GetSizeInBytes(); +} +CIMGUI_API int ImTextureData_GetPitch(ImTextureData* self) +{ + return self->GetPitch(); +} +CIMGUI_API void ImTextureData_GetTexRef(ImTextureRef *pOut,ImTextureData* self) +{ + *pOut = self->GetTexRef(); +} +CIMGUI_API ImTextureID ImTextureData_GetTexID(ImTextureData* self) +{ + return self->GetTexID(); +} +CIMGUI_API void ImTextureData_SetTexID(ImTextureData* self,ImTextureID tex_id) +{ + return self->SetTexID(tex_id); +} +CIMGUI_API void ImTextureData_SetStatus(ImTextureData* self,ImTextureStatus status) +{ + return self->SetStatus(status); +} CIMGUI_API ImFontConfig* ImFontConfig_ImFontConfig(void) { return IM_NEW(ImFontConfig)(); @@ -2503,6 +2678,14 @@ CIMGUI_API void ImFontConfig_destroy(ImFontConfig* self) { IM_DELETE(self); } +CIMGUI_API ImFontGlyph* ImFontGlyph_ImFontGlyph(void) +{ + return IM_NEW(ImFontGlyph)(); +} +CIMGUI_API void ImFontGlyph_destroy(ImFontGlyph* self) +{ + IM_DELETE(self); +} CIMGUI_API ImFontGlyphRangesBuilder* ImFontGlyphRangesBuilder_ImFontGlyphRangesBuilder(void) { return IM_NEW(ImFontGlyphRangesBuilder)(); @@ -2539,18 +2722,14 @@ CIMGUI_API void ImFontGlyphRangesBuilder_BuildRanges(ImFontGlyphRangesBuilder* s { return self->BuildRanges(out_ranges); } -CIMGUI_API ImFontAtlasCustomRect* ImFontAtlasCustomRect_ImFontAtlasCustomRect(void) +CIMGUI_API ImFontAtlasRect* ImFontAtlasRect_ImFontAtlasRect(void) { - return IM_NEW(ImFontAtlasCustomRect)(); + return IM_NEW(ImFontAtlasRect)(); } -CIMGUI_API void ImFontAtlasCustomRect_destroy(ImFontAtlasCustomRect* self) +CIMGUI_API void ImFontAtlasRect_destroy(ImFontAtlasRect* self) { IM_DELETE(self); } -CIMGUI_API bool ImFontAtlasCustomRect_IsPacked(ImFontAtlasCustomRect* self) -{ - return self->IsPacked(); -} CIMGUI_API ImFontAtlas* ImFontAtlas_ImFontAtlas(void) { return IM_NEW(ImFontAtlas)(); @@ -2583,97 +2762,73 @@ CIMGUI_API ImFont* ImFontAtlas_AddFontFromMemoryCompressedBase85TTF(ImFontAtlas* { return self->AddFontFromMemoryCompressedBase85TTF(compressed_font_data_base85,size_pixels,font_cfg,glyph_ranges); } -CIMGUI_API void ImFontAtlas_ClearInputData(ImFontAtlas* self) +CIMGUI_API void ImFontAtlas_RemoveFont(ImFontAtlas* self,ImFont* font) { - return self->ClearInputData(); -} -CIMGUI_API void ImFontAtlas_ClearTexData(ImFontAtlas* self) -{ - return self->ClearTexData(); -} -CIMGUI_API void ImFontAtlas_ClearFonts(ImFontAtlas* self) -{ - return self->ClearFonts(); + return self->RemoveFont(font); } CIMGUI_API void ImFontAtlas_Clear(ImFontAtlas* self) { return self->Clear(); } -CIMGUI_API bool ImFontAtlas_Build(ImFontAtlas* self) +CIMGUI_API void ImFontAtlas_CompactCache(ImFontAtlas* self) { - return self->Build(); + return self->CompactCache(); } -CIMGUI_API void ImFontAtlas_GetTexDataAsAlpha8(ImFontAtlas* self,unsigned char** out_pixels,int* out_width,int* out_height,int* out_bytes_per_pixel) +CIMGUI_API void ImFontAtlas_ClearInputData(ImFontAtlas* self) { - return self->GetTexDataAsAlpha8(out_pixels,out_width,out_height,out_bytes_per_pixel); + return self->ClearInputData(); } -CIMGUI_API void ImFontAtlas_GetTexDataAsRGBA32(ImFontAtlas* self,unsigned char** out_pixels,int* out_width,int* out_height,int* out_bytes_per_pixel) +CIMGUI_API void ImFontAtlas_ClearFonts(ImFontAtlas* self) { - return self->GetTexDataAsRGBA32(out_pixels,out_width,out_height,out_bytes_per_pixel); + return self->ClearFonts(); } -CIMGUI_API bool ImFontAtlas_IsBuilt(ImFontAtlas* self) +CIMGUI_API void ImFontAtlas_ClearTexData(ImFontAtlas* self) { - return self->IsBuilt(); -} -CIMGUI_API void ImFontAtlas_SetTexID(ImFontAtlas* self,ImTextureID id) -{ - return self->SetTexID(id); + return self->ClearTexData(); } CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesDefault(ImFontAtlas* self) { return self->GetGlyphRangesDefault(); } -CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesGreek(ImFontAtlas* self) +CIMGUI_API ImFontAtlasRectId ImFontAtlas_AddCustomRect(ImFontAtlas* self,int width,int height,ImFontAtlasRect* out_r) { - return self->GetGlyphRangesGreek(); + return self->AddCustomRect(width,height,out_r); } -CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesKorean(ImFontAtlas* self) +CIMGUI_API void ImFontAtlas_RemoveCustomRect(ImFontAtlas* self,ImFontAtlasRectId id) { - return self->GetGlyphRangesKorean(); + return self->RemoveCustomRect(id); } -CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesJapanese(ImFontAtlas* self) +CIMGUI_API bool ImFontAtlas_GetCustomRect(ImFontAtlas* self,ImFontAtlasRectId id,ImFontAtlasRect* out_r) { - return self->GetGlyphRangesJapanese(); + return self->GetCustomRect(id,out_r); } -CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesChineseFull(ImFontAtlas* self) +CIMGUI_API ImFontBaked* ImFontBaked_ImFontBaked(void) { - return self->GetGlyphRangesChineseFull(); + return IM_NEW(ImFontBaked)(); } -CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesChineseSimplifiedCommon(ImFontAtlas* self) +CIMGUI_API void ImFontBaked_destroy(ImFontBaked* self) { - return self->GetGlyphRangesChineseSimplifiedCommon(); + IM_DELETE(self); } -CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesCyrillic(ImFontAtlas* self) +CIMGUI_API void ImFontBaked_ClearOutputData(ImFontBaked* self) { - return self->GetGlyphRangesCyrillic(); + return self->ClearOutputData(); } -CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesThai(ImFontAtlas* self) +CIMGUI_API ImFontGlyph* ImFontBaked_FindGlyph(ImFontBaked* self,ImWchar c) { - return self->GetGlyphRangesThai(); + return self->FindGlyph(c); } -CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesVietnamese(ImFontAtlas* self) +CIMGUI_API ImFontGlyph* ImFontBaked_FindGlyphNoFallback(ImFontBaked* self,ImWchar c) { - return self->GetGlyphRangesVietnamese(); + return self->FindGlyphNoFallback(c); } -CIMGUI_API int ImFontAtlas_AddCustomRectRegular(ImFontAtlas* self,int width,int height) +CIMGUI_API float ImFontBaked_GetCharAdvance(ImFontBaked* self,ImWchar c) { - return self->AddCustomRectRegular(width,height); + return self->GetCharAdvance(c); } -CIMGUI_API int ImFontAtlas_AddCustomRectFontGlyph(ImFontAtlas* self,ImFont* font,ImWchar id,int width,int height,float advance_x,const ImVec2 offset) +CIMGUI_API bool ImFontBaked_IsGlyphLoaded(ImFontBaked* self,ImWchar c) { - return self->AddCustomRectFontGlyph(font,id,width,height,advance_x,offset); -} -CIMGUI_API ImFontAtlasCustomRect* ImFontAtlas_GetCustomRectByIndex(ImFontAtlas* self,int index) -{ - return self->GetCustomRectByIndex(index); -} -CIMGUI_API void ImFontAtlas_CalcCustomRectUV(ImFontAtlas* self,const ImFontAtlasCustomRect* rect,ImVec2* out_uv_min,ImVec2* out_uv_max) -{ - return self->CalcCustomRectUV(rect,out_uv_min,out_uv_max); -} -CIMGUI_API bool ImFontAtlas_GetMouseCursorTexData(ImFontAtlas* self,ImGuiMouseCursor cursor,ImVec2* out_offset,ImVec2* out_size,ImVec2 out_uv_border[2],ImVec2 out_uv_fill[2]) -{ - return ImFontAtlasGetMouseCursorTexData(self, cursor,out_offset,out_size,out_uv_border,out_uv_fill); + return self->IsGlyphLoaded(c); } CIMGUI_API ImFont* ImFont_ImFont(void) { @@ -2683,17 +2838,9 @@ CIMGUI_API void ImFont_destroy(ImFont* self) { IM_DELETE(self); } -CIMGUI_API const ImFontGlyph* ImFont_FindGlyph(ImFont* self,ImWchar c) +CIMGUI_API bool ImFont_IsGlyphInFont(ImFont* self,ImWchar c) { - return self->FindGlyph(c); -} -CIMGUI_API const ImFontGlyph* ImFont_FindGlyphNoFallback(ImFont* self,ImWchar c) -{ - return self->FindGlyphNoFallback(c); -} -CIMGUI_API float ImFont_GetCharAdvance(ImFont* self,ImWchar c) -{ - return self->GetCharAdvance(c); + return self->IsGlyphInFont(c); } CIMGUI_API bool ImFont_IsLoaded(ImFont* self) { @@ -2703,41 +2850,33 @@ CIMGUI_API const char* ImFont_GetDebugName(ImFont* self) { return self->GetDebugName(); } +CIMGUI_API ImFontBaked* ImFont_GetFontBaked(ImFont* self,float font_size,float density) +{ + return self->GetFontBaked(font_size,density); +} CIMGUI_API void ImFont_CalcTextSizeA(ImVec2 *pOut,ImFont* self,float size,float max_width,float wrap_width,const char* text_begin,const char* text_end,const char** remaining) { *pOut = self->CalcTextSizeA(size,max_width,wrap_width,text_begin,text_end,remaining); } -CIMGUI_API const char* ImFont_CalcWordWrapPositionA(ImFont* self,float scale,const char* text,const char* text_end,float wrap_width) +CIMGUI_API const char* ImFont_CalcWordWrapPosition(ImFont* self,float size,const char* text,const char* text_end,float wrap_width) { - return self->CalcWordWrapPositionA(scale,text,text_end,wrap_width); + return self->CalcWordWrapPosition(size,text,text_end,wrap_width); } -CIMGUI_API void ImFont_RenderChar(ImFont* self,ImDrawList* draw_list,float size,const ImVec2 pos,ImU32 col,ImWchar c) +CIMGUI_API void ImFont_RenderChar(ImFont* self,ImDrawList* draw_list,float size,const ImVec2 pos,ImU32 col,ImWchar c,const ImVec4* cpu_fine_clip) { - return self->RenderChar(draw_list,size,pos,col,c); + return self->RenderChar(draw_list,size,pos,col,c,cpu_fine_clip); } CIMGUI_API void ImFont_RenderText(ImFont* self,ImDrawList* draw_list,float size,const ImVec2 pos,ImU32 col,const ImVec4 clip_rect,const char* text_begin,const char* text_end,float wrap_width,bool cpu_fine_clip) { return self->RenderText(draw_list,size,pos,col,clip_rect,text_begin,text_end,wrap_width,cpu_fine_clip); } -CIMGUI_API void ImFont_BuildLookupTable(ImFont* self) -{ - return self->BuildLookupTable(); -} CIMGUI_API void ImFont_ClearOutputData(ImFont* self) { return self->ClearOutputData(); } -CIMGUI_API void ImFont_GrowIndex(ImFont* self,int new_size) +CIMGUI_API void ImFont_AddRemapChar(ImFont* self,ImWchar from_codepoint,ImWchar to_codepoint) { - return self->GrowIndex(new_size); -} -CIMGUI_API void ImFont_AddGlyph(ImFont* self,const ImFontConfig* src_cfg,ImWchar c,float x0,float y0,float x1,float y1,float u0,float v0,float u1,float v1,float advance_x) -{ - return self->AddGlyph(src_cfg,c,x0,y0,x1,y1,u0,v0,u1,v1,advance_x); -} -CIMGUI_API void ImFont_AddRemapChar(ImFont* self,ImWchar dst,ImWchar src,bool overwrite_dst) -{ - return self->AddRemapChar(dst,src,overwrite_dst); + return self->AddRemapChar(from_codepoint,to_codepoint); } CIMGUI_API bool ImFont_IsGlyphRangeUnused(ImFont* self,unsigned int c_begin,unsigned int c_last) { @@ -2791,7 +2930,7 @@ CIMGUI_API ImGuiID igImHashStr(const char* data,size_t data_size,ImGuiID seed) { return ImHashStr(data,data_size,seed); } -CIMGUI_API void igImQsort(void* base,size_t count,size_t size_of_element,int(*compare_func)(const void*,const void*)) +CIMGUI_API void igImQsort(void* base,size_t count,size_t size_of_element,int(*compare_func)(void const*,void const*)) { return ImQsort(base,count,size_of_element,compare_func); } @@ -2811,6 +2950,10 @@ CIMGUI_API int igImUpperPowerOfTwo(int v) { return ImUpperPowerOfTwo(v); } +CIMGUI_API unsigned int igImCountSetBits(unsigned int v) +{ + return ImCountSetBits(v); +} CIMGUI_API int igImStricmp(const char* str1,const char* str2) { return ImStricmp(str1,str2); @@ -2827,6 +2970,10 @@ CIMGUI_API char* igImStrdup(const char* str) { return ImStrdup(str); } +CIMGUI_API void* igImMemdup(const void* src,size_t size) +{ + return ImMemdup(src,size); +} CIMGUI_API char* igImStrdupcpy(char* dst,size_t* p_dst_size,const char* str) { return ImStrdupcpy(dst,p_dst_size,str); @@ -2855,6 +3002,10 @@ CIMGUI_API int igImStrlenW(const ImWchar* str) { return ImStrlenW(str); } +CIMGUI_API const char* igImStrbol(const char* buf_mid_line,const char* buf_begin) +{ + return ImStrbol(buf_mid_line,buf_begin); +} CIMGUI_API char igImToUpper(char c) { return ImToUpper(c); @@ -2879,6 +3030,12 @@ CIMGUI_API int igImFormatString(char* buf,size_t buf_size,const char* fmt,...) va_end(args); return ret; } +#ifdef CIMGUI_VARGS0 +CIMGUI_API int igImFormatString0(char* buf,size_t buf_size,const char* fmt) +{ + return igImFormatString(buf,buf_size,fmt); +} +#endif CIMGUI_API int igImFormatStringV(char* buf,size_t buf_size,const char* fmt,va_list args) { return ImFormatStringV(buf,buf_size,fmt,args); @@ -2890,6 +3047,12 @@ CIMGUI_API void igImFormatStringToTempBuffer(const char** out_buf,const char** o ImFormatStringToTempBufferV(out_buf,out_buf_end,fmt,args); va_end(args); } +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igImFormatStringToTempBuffer0(const char** out_buf,const char** out_buf_end,const char* fmt) +{ + return igImFormatStringToTempBuffer(out_buf,out_buf_end,fmt); +} +#endif CIMGUI_API void igImFormatStringToTempBufferV(const char** out_buf,const char** out_buf_end,const char* fmt,va_list args) { return ImFormatStringToTempBufferV(out_buf,out_buf_end,fmt,args); @@ -3078,6 +3241,14 @@ CIMGUI_API void igImFloor_Vec2(ImVec2 *pOut,const ImVec2 v) { *pOut = ImFloor(v); } +CIMGUI_API float igImTrunc64(float f) +{ + return ImTrunc64(f); +} +CIMGUI_API float igImRound64(float f) +{ + return ImRound64(f); +} CIMGUI_API int igImModPositive(int a,int b) { return ImModPositive(a,b); @@ -3162,6 +3333,18 @@ CIMGUI_API ImVec1* ImVec1_ImVec1_Float(float _x) { return IM_NEW(ImVec1)(_x); } +CIMGUI_API ImVec2i* ImVec2i_ImVec2i_Nil(void) +{ + return IM_NEW(ImVec2i)(); +} +CIMGUI_API void ImVec2i_destroy(ImVec2i* self) +{ + IM_DELETE(self); +} +CIMGUI_API ImVec2i* ImVec2i_ImVec2i_Int(int _x,int _y) +{ + return IM_NEW(ImVec2i)(_x,_y); +} CIMGUI_API ImVec2ih* ImVec2ih_ImVec2ih_Nil(void) { return IM_NEW(ImVec2ih)(); @@ -3458,13 +3641,18 @@ CIMGUI_API void ImGuiInputTextState_ClearText(ImGuiInputTextState* self) { return self->ClearText(); } -CIMGUI_API void ImGuiInputTextState_ClearFreeMemory(ImGuiInputTextState* self) { +CIMGUI_API void ImGuiInputTextState_ClearFreeMemory(ImGuiInputTextState* self) +{ return self->ClearFreeMemory(); } CIMGUI_API void ImGuiInputTextState_OnKeyPressed(ImGuiInputTextState* self,int key) { return self->OnKeyPressed(key); } +CIMGUI_API void ImGuiInputTextState_OnCharPressed(ImGuiInputTextState* self,unsigned int c) +{ + return self->OnCharPressed(c); +} CIMGUI_API void ImGuiInputTextState_CursorAnimReset(ImGuiInputTextState* self) { return self->CursorAnimReset(); @@ -3541,6 +3729,14 @@ CIMGUI_API void ImGuiLastItemData_destroy(ImGuiLastItemData* self) { IM_DELETE(self); } +CIMGUI_API ImGuiErrorRecoveryState* ImGuiErrorRecoveryState_ImGuiErrorRecoveryState(void) +{ + return IM_NEW(ImGuiErrorRecoveryState)(); +} +CIMGUI_API void ImGuiErrorRecoveryState_destroy(ImGuiErrorRecoveryState* self) +{ + IM_DELETE(self); +} CIMGUI_API ImGuiPtrOrIndex* ImGuiPtrOrIndex_ImGuiPtrOrIndex_Ptr(void* ptr) { return IM_NEW(ImGuiPtrOrIndex)(ptr); @@ -3765,13 +3961,13 @@ CIMGUI_API void ImGuiViewportP_ClearRequestFlags(ImGuiViewportP* self) { return self->ClearRequestFlags(); } -CIMGUI_API void ImGuiViewportP_CalcWorkRectPos(ImVec2 *pOut,ImGuiViewportP* self,const ImVec2 off_min) +CIMGUI_API void ImGuiViewportP_CalcWorkRectPos(ImVec2 *pOut,ImGuiViewportP* self,const ImVec2 inset_min) { - *pOut = self->CalcWorkRectPos(off_min); + *pOut = self->CalcWorkRectPos(inset_min); } -CIMGUI_API void ImGuiViewportP_CalcWorkRectSize(ImVec2 *pOut,ImGuiViewportP* self,const ImVec2 off_min,const ImVec2 off_max) +CIMGUI_API void ImGuiViewportP_CalcWorkRectSize(ImVec2 *pOut,ImGuiViewportP* self,const ImVec2 inset_min,const ImVec2 inset_max) { - *pOut = self->CalcWorkRectSize(off_min,off_max); + *pOut = self->CalcWorkRectSize(inset_min,inset_max); } CIMGUI_API void ImGuiViewportP_UpdateWorkRect(ImGuiViewportP* self) { @@ -3869,6 +4065,10 @@ CIMGUI_API ImGuiID ImGuiWindow_GetID_Int(ImGuiWindow* self,int n) { return self->GetID(n); } +CIMGUI_API ImGuiID ImGuiWindow_GetIDFromPos(ImGuiWindow* self,const ImVec2 p_abs) +{ + return self->GetIDFromPos(p_abs); +} CIMGUI_API ImGuiID ImGuiWindow_GetIDFromRectangle(ImGuiWindow* self,const ImRect r_abs) { return self->GetIDFromRectangle(r_abs); @@ -3877,10 +4077,6 @@ CIMGUI_API void ImGuiWindow_Rect(ImRect *pOut,ImGuiWindow* self) { *pOut = self->Rect(); } -CIMGUI_API float ImGuiWindow_CalcFontSize(ImGuiWindow* self) -{ - return self->CalcFontSize(); -} CIMGUI_API void ImGuiWindow_TitleBarRect(ImRect *pOut,ImGuiWindow* self) { *pOut = self->TitleBarRect(); @@ -3957,6 +4153,14 @@ CIMGUI_API ImGuiTableColumnSettings* ImGuiTableSettings_GetColumnSettings(ImGuiT { return self->GetColumnSettings(); } +CIMGUI_API ImGuiIO* igGetIO_ContextPtr(ImGuiContext* ctx) +{ + return &ImGui::GetIO(ctx); +} +CIMGUI_API ImGuiPlatformIO* igGetPlatformIO_ContextPtr(ImGuiContext* ctx) +{ + return &ImGui::GetPlatformIO(ctx); +} CIMGUI_API ImGuiWindow* igGetCurrentWindowRead() { return ImGui::GetCurrentWindowRead(); @@ -4033,14 +4237,14 @@ CIMGUI_API void igWindowRectRelToAbs(ImRect *pOut,ImGuiWindow* window,const ImRe { *pOut = ImGui::WindowRectRelToAbs(window,r); } -CIMGUI_API void igWindowPosRelToAbs(ImVec2 *pOut,ImGuiWindow* window,const ImVec2 p) -{ - *pOut = ImGui::WindowPosRelToAbs(window,p); -} CIMGUI_API void igWindowPosAbsToRel(ImVec2 *pOut,ImGuiWindow* window,const ImVec2 p) { *pOut = ImGui::WindowPosAbsToRel(window,p); } +CIMGUI_API void igWindowPosRelToAbs(ImVec2 *pOut,ImGuiWindow* window,const ImVec2 p) +{ + *pOut = ImGui::WindowPosRelToAbs(window,p); +} CIMGUI_API void igFocusWindow(ImGuiWindow* window,ImGuiFocusRequestFlags flags) { return ImGui::FocusWindow(window,flags); @@ -4077,14 +4281,54 @@ CIMGUI_API void igSetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags) { return ImGui::SetNextWindowRefreshPolicy(flags); } -CIMGUI_API void igSetCurrentFont(ImFont* font) +CIMGUI_API void igRegisterUserTexture(ImTextureData* tex) { - return ImGui::SetCurrentFont(font); + return ImGui::RegisterUserTexture(tex); +} +CIMGUI_API void igUnregisterUserTexture(ImTextureData* tex) +{ + return ImGui::UnregisterUserTexture(tex); +} +CIMGUI_API void igRegisterFontAtlas(ImFontAtlas* atlas) +{ + return ImGui::RegisterFontAtlas(atlas); +} +CIMGUI_API void igUnregisterFontAtlas(ImFontAtlas* atlas) +{ + return ImGui::UnregisterFontAtlas(atlas); +} +CIMGUI_API void igSetCurrentFont(ImFont* font,float font_size_before_scaling,float font_size_after_scaling) +{ + return ImGui::SetCurrentFont(font,font_size_before_scaling,font_size_after_scaling); +} +CIMGUI_API void igUpdateCurrentFontSize(float restore_font_size_after_scaling) +{ + return ImGui::UpdateCurrentFontSize(restore_font_size_after_scaling); +} +CIMGUI_API void igSetFontRasterizerDensity(float rasterizer_density) +{ + return ImGui::SetFontRasterizerDensity(rasterizer_density); +} +CIMGUI_API float igGetFontRasterizerDensity() +{ + return ImGui::GetFontRasterizerDensity(); +} +CIMGUI_API float igGetRoundedFontSize(float size) +{ + return ImGui::GetRoundedFontSize(size); } CIMGUI_API ImFont* igGetDefaultFont() { return ImGui::GetDefaultFont(); } +CIMGUI_API void igPushPasswordFont() +{ + return ImGui::PushPasswordFont(); +} +CIMGUI_API void igPopPasswordFont() +{ + return ImGui::PopPasswordFont(); +} CIMGUI_API ImDrawList* igGetForegroundDrawList_WindowPtr(ImGuiWindow* window) { return ImGui::GetForegroundDrawList(window); @@ -4105,9 +4349,9 @@ CIMGUI_API void igUpdateInputEvents(bool trickle_fast_inputs) { return ImGui::UpdateInputEvents(trickle_fast_inputs); } -CIMGUI_API void igUpdateHoveredWindowAndCaptureFlags() +CIMGUI_API void igUpdateHoveredWindowAndCaptureFlags(const ImVec2 mouse_pos) { - return ImGui::UpdateHoveredWindowAndCaptureFlags(); + return ImGui::UpdateHoveredWindowAndCaptureFlags(mouse_pos); } CIMGUI_API void igFindHoveredWindowEx(const ImVec2 pos,bool find_first_and_in_any_viewport,ImGuiWindow** out_hovered_window,ImGuiWindow** out_hovered_window_under_moving_window) { @@ -4329,9 +4573,9 @@ CIMGUI_API bool igIsClippedEx(const ImRect bb,ImGuiID id) { return ImGui::IsClippedEx(bb,id); } -CIMGUI_API void igSetLastItemData(ImGuiID item_id,ImGuiItemFlags in_flags,ImGuiItemStatusFlags status_flags,const ImRect item_rect) +CIMGUI_API void igSetLastItemData(ImGuiID item_id,ImGuiItemFlags item_flags,ImGuiItemStatusFlags status_flags,const ImRect item_rect) { - return ImGui::SetLastItemData(item_id,in_flags,status_flags,item_rect); + return ImGui::SetLastItemData(item_id,item_flags,status_flags,item_rect); } CIMGUI_API void igCalcItemSize(ImVec2 *pOut,ImVec2 size,float default_w,float default_h) { @@ -4385,6 +4629,10 @@ CIMGUI_API bool igBeginPopupEx(ImGuiID id,ImGuiWindowFlags extra_window_flags) { return ImGui::BeginPopupEx(id,extra_window_flags); } +CIMGUI_API bool igBeginPopupMenuEx(ImGuiID id,const char* label,ImGuiWindowFlags extra_window_flags) +{ + return ImGui::BeginPopupMenuEx(id,label,extra_window_flags); +} CIMGUI_API void igOpenPopupEx(ImGuiID id,ImGuiPopupFlags popup_flags) { return ImGui::OpenPopupEx(id,popup_flags); @@ -4485,7 +4733,7 @@ CIMGUI_API void igNavMoveRequestResolveWithLastItem(ImGuiNavItemData* result) { return ImGui::NavMoveRequestResolveWithLastItem(result); } -CIMGUI_API void igNavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result,ImGuiTreeNodeStackData* tree_node_data) +CIMGUI_API void igNavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result,const ImGuiTreeNodeStackData* tree_node_data) { return ImGui::NavMoveRequestResolveWithPastTreeNode(result,tree_node_data); } @@ -4509,6 +4757,10 @@ CIMGUI_API void igNavClearPreferredPosForAxis(ImGuiAxis axis) { return ImGui::NavClearPreferredPosForAxis(axis); } +CIMGUI_API void igSetNavCursorVisibleAfterMove() +{ + return ImGui::SetNavCursorVisibleAfterMove(); +} CIMGUI_API void igNavUpdateCurrentWindowIsScrollPushableX() { return ImGui::NavUpdateCurrentWindowIsScrollPushableX(); @@ -4561,6 +4813,10 @@ CIMGUI_API bool igIsAliasKey(ImGuiKey key) { return ImGui::IsAliasKey(key); } +CIMGUI_API bool igIsLRModKey(ImGuiKey key) +{ + return ImGui::IsLRModKey(key); +} CIMGUI_API ImGuiKeyChord igFixupKeyChord(ImGuiKeyChord key_chord) { return ImGui::FixupKeyChord(key_chord); @@ -5009,6 +5265,14 @@ CIMGUI_API void igTablePopBackgroundChannel() { return ImGui::TablePopBackgroundChannel(); } +CIMGUI_API void igTablePushColumnChannel(int column_n) +{ + return ImGui::TablePushColumnChannel(column_n); +} +CIMGUI_API void igTablePopColumnChannel() +{ + return ImGui::TablePopColumnChannel(); +} CIMGUI_API void igTableAngledHeadersRowEx(ImGuiID row_id,float angle,float max_label_width,const ImGuiTableHeaderData* data,int data_count) { return ImGui::TableAngledHeadersRowEx(row_id,angle,max_label_width,data,data_count); @@ -5121,6 +5385,10 @@ CIMGUI_API ImGuiID igTableGetColumnResizeID(ImGuiTable* table,int column_n,int i { return ImGui::TableGetColumnResizeID(table,column_n,instance_no); } +CIMGUI_API float igTableCalcMaxColumnWidth(const ImGuiTable* table,int column_n) +{ + return ImGui::TableCalcMaxColumnWidth(table,column_n); +} CIMGUI_API void igTableSetColumnWidthAutoSingle(ImGuiTable* table,int column_n) { return ImGui::TableSetColumnWidthAutoSingle(table,column_n); @@ -5217,10 +5485,14 @@ CIMGUI_API void igTabBarCloseTab(ImGuiTabBar* tab_bar,ImGuiTabItem* tab) { return ImGui::TabBarCloseTab(tab_bar,tab); } -CIMGUI_API void igTabBarQueueFocus(ImGuiTabBar* tab_bar,ImGuiTabItem* tab) +CIMGUI_API void igTabBarQueueFocus_TabItemPtr(ImGuiTabBar* tab_bar,ImGuiTabItem* tab) { return ImGui::TabBarQueueFocus(tab_bar,tab); } +CIMGUI_API void igTabBarQueueFocus_Str(ImGuiTabBar* tab_bar,const char* tab_name) +{ + return ImGui::TabBarQueueFocus(tab_bar,tab_name); +} CIMGUI_API void igTabBarQueueReorder(ImGuiTabBar* tab_bar,ImGuiTabItem* tab,int offset) { return ImGui::TabBarQueueReorder(tab_bar,tab,offset); @@ -5237,6 +5509,10 @@ CIMGUI_API bool igTabItemEx(ImGuiTabBar* tab_bar,const char* label,bool* p_open, { return ImGui::TabItemEx(tab_bar,label,p_open,flags,docked_window); } +CIMGUI_API void igTabItemSpacing(const char* str_id,ImGuiTabItemFlags flags,float width) +{ + return ImGui::TabItemSpacing(str_id,flags,width); +} CIMGUI_API void igTabItemCalcSize_Str(ImVec2 *pOut,const char* label,bool has_close_button_or_unsaved_marker) { *pOut = ImGui::TabItemCalcSize(label,has_close_button_or_unsaved_marker); @@ -5269,13 +5545,13 @@ CIMGUI_API void igRenderTextClippedEx(ImDrawList* draw_list,const ImVec2 pos_min { return ImGui::RenderTextClippedEx(draw_list,pos_min,pos_max,text,text_end,text_size_if_known,align,clip_rect); } -CIMGUI_API void igRenderTextEllipsis(ImDrawList* draw_list,const ImVec2 pos_min,const ImVec2 pos_max,float clip_max_x,float ellipsis_max_x,const char* text,const char* text_end,const ImVec2* text_size_if_known) +CIMGUI_API void igRenderTextEllipsis(ImDrawList* draw_list,const ImVec2 pos_min,const ImVec2 pos_max,float ellipsis_max_x,const char* text,const char* text_end,const ImVec2* text_size_if_known) { - return ImGui::RenderTextEllipsis(draw_list,pos_min,pos_max,clip_max_x,ellipsis_max_x,text,text_end,text_size_if_known); + return ImGui::RenderTextEllipsis(draw_list,pos_min,pos_max,ellipsis_max_x,text,text_end,text_size_if_known); } -CIMGUI_API void igRenderFrame(ImVec2 p_min,ImVec2 p_max,ImU32 fill_col,bool border,float rounding) +CIMGUI_API void igRenderFrame(ImVec2 p_min,ImVec2 p_max,ImU32 fill_col,bool borders,float rounding) { - return ImGui::RenderFrame(p_min,p_max,fill_col,border,rounding); + return ImGui::RenderFrame(p_min,p_max,fill_col,borders,rounding); } CIMGUI_API void igRenderFrameBorder(ImVec2 p_min,ImVec2 p_max,float rounding) { @@ -5285,6 +5561,10 @@ CIMGUI_API void igRenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list,ImV { return ImGui::RenderColorRectWithAlphaCheckerboard(draw_list,p_min,p_max,fill_col,grid_step,grid_off,rounding,flags); } +CIMGUI_API void igRenderNavCursor(const ImRect bb,ImGuiID id,ImGuiNavRenderCursorFlags flags) +{ + return ImGui::RenderNavCursor(bb,id,flags); +} CIMGUI_API const char* igFindRenderedTextEnd(const char* text,const char* text_end) { return ImGui::FindRenderedTextEnd(text,text_end); @@ -5329,6 +5609,23 @@ CIMGUI_API void igTextEx(const char* text,const char* text_end,ImGuiTextFlags fl { return ImGui::TextEx(text,text_end,flags); } +CIMGUI_API void igTextAligned(float align_x,float size_x,const char* fmt,...) +{ + va_list args; + va_start(args, fmt); + ImGui::TextAlignedV(align_x,size_x,fmt,args); + va_end(args); +} +#ifdef CIMGUI_VARGS0 +CIMGUI_API void igTextAligned0(float align_x,float size_x,const char* fmt) +{ + return igTextAligned(align_x,size_x,fmt); +} +#endif +CIMGUI_API void igTextAlignedV(float align_x,float size_x,const char* fmt,va_list args) +{ + return ImGui::TextAlignedV(align_x,size_x,fmt,args); +} CIMGUI_API bool igButtonEx(const char* label,const ImVec2 size_arg,ImGuiButtonFlags flags) { return ImGui::ButtonEx(label,size_arg,flags); @@ -5337,9 +5634,9 @@ CIMGUI_API bool igArrowButtonEx(const char* str_id,ImGuiDir dir,ImVec2 size_arg, { return ImGui::ArrowButtonEx(str_id,dir,size_arg,flags); } -CIMGUI_API bool igImageButtonEx(ImGuiID id,ImTextureID texture_id,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1,const ImVec4 bg_col,const ImVec4 tint_col,ImGuiButtonFlags flags) +CIMGUI_API bool igImageButtonEx(ImGuiID id,ImTextureRef tex_ref,const ImVec2 image_size,const ImVec2 uv0,const ImVec2 uv1,const ImVec4 bg_col,const ImVec4 tint_col,ImGuiButtonFlags flags) { - return ImGui::ImageButtonEx(id,texture_id,image_size,uv0,uv1,bg_col,tint_col,flags); + return ImGui::ImageButtonEx(id,tex_ref,image_size,uv0,uv1,bg_col,tint_col,flags); } CIMGUI_API void igSeparatorEx(ImGuiSeparatorFlags flags,float thickness) { @@ -5369,9 +5666,9 @@ CIMGUI_API void igScrollbar(ImGuiAxis axis) { return ImGui::Scrollbar(axis); } -CIMGUI_API bool igScrollbarEx(const ImRect bb,ImGuiID id,ImGuiAxis axis,ImS64* p_scroll_v,ImS64 avail_v,ImS64 contents_v,ImDrawFlags flags) +CIMGUI_API bool igScrollbarEx(const ImRect bb,ImGuiID id,ImGuiAxis axis,ImS64* p_scroll_v,ImS64 avail_v,ImS64 contents_v,ImDrawFlags draw_rounding_flags) { - return ImGui::ScrollbarEx(bb,id,axis,p_scroll_v,avail_v,contents_v,flags); + return ImGui::ScrollbarEx(bb,id,axis,p_scroll_v,avail_v,contents_v,draw_rounding_flags); } CIMGUI_API void igGetWindowScrollbarRect(ImRect *pOut,ImGuiWindow* window,ImGuiAxis axis) { @@ -5409,6 +5706,14 @@ CIMGUI_API bool igTreeNodeBehavior(ImGuiID id,ImGuiTreeNodeFlags flags,const cha { return ImGui::TreeNodeBehavior(id,flags,label,label_end); } +CIMGUI_API void igTreeNodeDrawLineToChildNode(const ImVec2 target_pos) +{ + return ImGui::TreeNodeDrawLineToChildNode(target_pos); +} +CIMGUI_API void igTreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data) +{ + return ImGui::TreeNodeDrawLineToTreePop(data); +} CIMGUI_API void igTreePushOverrideID(ImGuiID id) { return ImGui::TreePushOverrideID(id); @@ -5449,6 +5754,10 @@ CIMGUI_API bool igDataTypeClamp(ImGuiDataType data_type,void* p_data,const void* { return ImGui::DataTypeClamp(data_type,p_data,p_min,p_max); } +CIMGUI_API bool igDataTypeIsZero(ImGuiDataType data_type,const void* p_data) +{ + return ImGui::DataTypeIsZero(data_type,p_data); +} CIMGUI_API bool igInputTextEx(const char* label,const char* hint,char* buf,int buf_size,const ImVec2 size_arg,ImGuiInputTextFlags flags,ImGuiInputTextCallback callback,void* user_data) { return ImGui::InputTextEx(label,hint,buf,buf_size,size_arg,flags,callback,user_data); @@ -5477,6 +5786,10 @@ CIMGUI_API void igSetNextItemRefVal(ImGuiDataType data_type,void* p_data) { return ImGui::SetNextItemRefVal(data_type,p_data); } +CIMGUI_API bool igIsItemActiveAsInputText() +{ + return ImGui::IsItemActiveAsInputText(); +} CIMGUI_API void igColorTooltip(const char* text,const float* col,ImGuiColorEditFlags flags) { return ImGui::ColorTooltip(text,col,flags); @@ -5517,14 +5830,42 @@ CIMGUI_API void igGcAwakeTransientWindowBuffers(ImGuiWindow* window) { return ImGui::GcAwakeTransientWindowBuffers(window); } -CIMGUI_API void igDebugAllocHook(ImGuiDebugAllocInfo* info,int frame_count,void* ptr,size_t size) +CIMGUI_API bool igErrorLog(const char* msg) { - return ImGui::DebugAllocHook(info,frame_count,ptr,size); + return ImGui::ErrorLog(msg); +} +CIMGUI_API void igErrorRecoveryStoreState(ImGuiErrorRecoveryState* state_out) +{ + return ImGui::ErrorRecoveryStoreState(state_out); +} +CIMGUI_API void igErrorRecoveryTryToRecoverState(const ImGuiErrorRecoveryState* state_in) +{ + return ImGui::ErrorRecoveryTryToRecoverState(state_in); +} +CIMGUI_API void igErrorRecoveryTryToRecoverWindowState(const ImGuiErrorRecoveryState* state_in) +{ + return ImGui::ErrorRecoveryTryToRecoverWindowState(state_in); } CIMGUI_API void igErrorCheckUsingSetCursorPosToExtendParentBoundaries() { return ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries(); } +CIMGUI_API void igErrorCheckEndFrameFinalizeErrorTooltip() +{ + return ImGui::ErrorCheckEndFrameFinalizeErrorTooltip(); +} +CIMGUI_API bool igBeginErrorTooltip() +{ + return ImGui::BeginErrorTooltip(); +} +CIMGUI_API void igEndErrorTooltip() +{ + return ImGui::EndErrorTooltip(); +} +CIMGUI_API void igDebugAllocHook(ImGuiDebugAllocInfo* info,int frame_count,void* ptr,size_t size) +{ + return ImGui::DebugAllocHook(info,frame_count,ptr,size); +} CIMGUI_API void igDebugDrawCursorPos(ImU32 col) { return ImGui::DebugDrawCursorPos(col); @@ -5593,10 +5934,18 @@ CIMGUI_API void igDebugNodeFont(ImFont* font) { return ImGui::DebugNodeFont(font); } +CIMGUI_API void igDebugNodeFontGlyphesForSrcMask(ImFont* font,ImFontBaked* baked,int src_mask) +{ + return ImGui::DebugNodeFontGlyphesForSrcMask(font,baked,src_mask); +} CIMGUI_API void igDebugNodeFontGlyph(ImFont* font,const ImFontGlyph* glyph) { return ImGui::DebugNodeFontGlyph(font,glyph); } +CIMGUI_API void igDebugNodeTexture(ImTextureData* tex,int int_id,const ImFontAtlasRect* highlight_rect) +{ + return ImGui::DebugNodeTexture(tex,int_id,highlight_rect); +} CIMGUI_API void igDebugNodeStorage(ImGuiStorage* storage,const char* label) { return ImGui::DebugNodeStorage(storage,label); @@ -5657,57 +6006,269 @@ CIMGUI_API void igDebugRenderViewportThumbnail(ImDrawList* draw_list,ImGuiViewpo { return ImGui::DebugRenderViewportThumbnail(draw_list,viewport,bb); } +CIMGUI_API ImFontLoader* ImFontLoader_ImFontLoader(void) +{ + return IM_NEW(ImFontLoader)(); +} +CIMGUI_API void ImFontLoader_destroy(ImFontLoader* self) +{ + IM_DELETE(self); +} +CIMGUI_API int igImFontAtlasRectId_GetIndex(ImFontAtlasRectId id) +{ + return ImFontAtlasRectId_GetIndex(id); +} +CIMGUI_API int igImFontAtlasRectId_GetGeneration(ImFontAtlasRectId id) +{ + return ImFontAtlasRectId_GetGeneration(id); +} +CIMGUI_API ImFontAtlasRectId igImFontAtlasRectId_Make(int index_idx,int gen_idx) +{ + return ImFontAtlasRectId_Make(index_idx,gen_idx); +} +CIMGUI_API ImFontAtlasBuilder* ImFontAtlasBuilder_ImFontAtlasBuilder(void) +{ + return IM_NEW(ImFontAtlasBuilder)(); +} +CIMGUI_API void ImFontAtlasBuilder_destroy(ImFontAtlasBuilder* self) +{ + IM_DELETE(self); +} CIMGUI_API void igImFontAtlasBuildInit(ImFontAtlas* atlas) { return ImFontAtlasBuildInit(atlas); } -CIMGUI_API void igImFontAtlasBuildSetupFont(ImFontAtlas* atlas,ImFont* font,ImFontConfig* font_config,float ascent,float descent) +CIMGUI_API void igImFontAtlasBuildDestroy(ImFontAtlas* atlas) { - return ImFontAtlasBuildSetupFont(atlas,font,font_config,ascent,descent); + return ImFontAtlasBuildDestroy(atlas); } -CIMGUI_API void igImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas,void* stbrp_context_opaque) +CIMGUI_API void igImFontAtlasBuildMain(ImFontAtlas* atlas) { - return ImFontAtlasBuildPackCustomRects(atlas,stbrp_context_opaque); + return ImFontAtlasBuildMain(atlas); } -CIMGUI_API void igImFontAtlasBuildFinish(ImFontAtlas* atlas) +CIMGUI_API void igImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas,const ImFontLoader* font_loader) { - return ImFontAtlasBuildFinish(atlas); + return ImFontAtlasBuildSetupFontLoader(atlas,font_loader); } -CIMGUI_API void igImFontAtlasBuildRender8bppRectFromString(ImFontAtlas* atlas,int x,int y,int w,int h,const char* in_str,char in_marker_char,unsigned char in_marker_pixel_value) +CIMGUI_API void igImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas) { - return ImFontAtlasBuildRender8bppRectFromString(atlas,x,y,w,h,in_str,in_marker_char,in_marker_pixel_value); + return ImFontAtlasBuildUpdatePointers(atlas); } -CIMGUI_API void igImFontAtlasBuildRender32bppRectFromString(ImFontAtlas* atlas,int x,int y,int w,int h,const char* in_str,char in_marker_char,unsigned int in_marker_pixel_value) +CIMGUI_API void igImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas,int x,int y,int w,int h,const char* in_str,char in_marker_char) { - return ImFontAtlasBuildRender32bppRectFromString(atlas,x,y,w,h,in_str,in_marker_char,in_marker_pixel_value); + return ImFontAtlasBuildRenderBitmapFromString(atlas,x,y,w,h,in_str,in_marker_char); } -CIMGUI_API void igImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256],float in_multiply_factor) +CIMGUI_API void igImFontAtlasBuildClear(ImFontAtlas* atlas) { - return ImFontAtlasBuildMultiplyCalcLookupTable(out_table,in_multiply_factor); + return ImFontAtlasBuildClear(atlas); } -CIMGUI_API void igImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256],unsigned char* pixels,int x,int y,int w,int h,int stride) +CIMGUI_API ImTextureData* igImFontAtlasTextureAdd(ImFontAtlas* atlas,int w,int h) { - return ImFontAtlasBuildMultiplyRectAlpha8(table,pixels,x,y,w,h,stride); + return ImFontAtlasTextureAdd(atlas,w,h); } +CIMGUI_API void igImFontAtlasTextureMakeSpace(ImFontAtlas* atlas) +{ + return ImFontAtlasTextureMakeSpace(atlas); +} +CIMGUI_API void igImFontAtlasTextureRepack(ImFontAtlas* atlas,int w,int h) +{ + return ImFontAtlasTextureRepack(atlas,w,h); +} +CIMGUI_API void igImFontAtlasTextureGrow(ImFontAtlas* atlas,int old_w,int old_h) +{ + return ImFontAtlasTextureGrow(atlas,old_w,old_h); +} +CIMGUI_API void igImFontAtlasTextureCompact(ImFontAtlas* atlas) +{ + return ImFontAtlasTextureCompact(atlas); +} +CIMGUI_API void igImFontAtlasTextureGetSizeEstimate(ImVec2i *pOut,ImFontAtlas* atlas) +{ + *pOut = ImFontAtlasTextureGetSizeEstimate(atlas); +} +CIMGUI_API void igImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas,ImFont* font,ImFontConfig* src) +{ + return ImFontAtlasBuildSetupFontSpecialGlyphs(atlas,font,src); +} +CIMGUI_API void igImFontAtlasBuildLegacyPreloadAllGlyphRanges(ImFontAtlas* atlas) +{ + return ImFontAtlasBuildLegacyPreloadAllGlyphRanges(atlas); +} +CIMGUI_API void igImFontAtlasBuildGetOversampleFactors(ImFontConfig* src,ImFontBaked* baked,int* out_oversample_h,int* out_oversample_v) +{ + return ImFontAtlasBuildGetOversampleFactors(src,baked,out_oversample_h,out_oversample_v); +} +CIMGUI_API void igImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas,int unused_frames) +{ + return ImFontAtlasBuildDiscardBakes(atlas,unused_frames); +} +CIMGUI_API bool igImFontAtlasFontSourceInit(ImFontAtlas* atlas,ImFontConfig* src) +{ + return ImFontAtlasFontSourceInit(atlas,src); +} +CIMGUI_API void igImFontAtlasFontSourceAddToFont(ImFontAtlas* atlas,ImFont* font,ImFontConfig* src) +{ + return ImFontAtlasFontSourceAddToFont(atlas,font,src); +} +CIMGUI_API void igImFontAtlasFontDestroySourceData(ImFontAtlas* atlas,ImFontConfig* src) +{ + return ImFontAtlasFontDestroySourceData(atlas,src); +} +CIMGUI_API bool igImFontAtlasFontInitOutput(ImFontAtlas* atlas,ImFont* font) +{ + return ImFontAtlasFontInitOutput(atlas,font); +} +CIMGUI_API void igImFontAtlasFontDestroyOutput(ImFontAtlas* atlas,ImFont* font) +{ + return ImFontAtlasFontDestroyOutput(atlas,font); +} +CIMGUI_API void igImFontAtlasFontDiscardBakes(ImFontAtlas* atlas,ImFont* font,int unused_frames) +{ + return ImFontAtlasFontDiscardBakes(atlas,font,unused_frames); +} +CIMGUI_API ImGuiID igImFontAtlasBakedGetId(ImGuiID font_id,float baked_size,float rasterizer_density) +{ + return ImFontAtlasBakedGetId(font_id,baked_size,rasterizer_density); +} +CIMGUI_API ImFontBaked* igImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas,ImFont* font,float font_size,float font_rasterizer_density) +{ + return ImFontAtlasBakedGetOrAdd(atlas,font,font_size,font_rasterizer_density); +} +CIMGUI_API ImFontBaked* igImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas,ImFont* font,float font_size,float font_rasterizer_density) +{ + return ImFontAtlasBakedGetClosestMatch(atlas,font,font_size,font_rasterizer_density); +} +CIMGUI_API ImFontBaked* igImFontAtlasBakedAdd(ImFontAtlas* atlas,ImFont* font,float font_size,float font_rasterizer_density,ImGuiID baked_id) +{ + return ImFontAtlasBakedAdd(atlas,font,font_size,font_rasterizer_density,baked_id); +} +CIMGUI_API void igImFontAtlasBakedDiscard(ImFontAtlas* atlas,ImFont* font,ImFontBaked* baked) +{ + return ImFontAtlasBakedDiscard(atlas,font,baked); +} +CIMGUI_API ImFontGlyph* igImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas,ImFontBaked* baked,ImFontConfig* src,const ImFontGlyph* in_glyph) +{ + return ImFontAtlasBakedAddFontGlyph(atlas,baked,src,in_glyph); +} +CIMGUI_API void igImFontAtlasBakedDiscardFontGlyph(ImFontAtlas* atlas,ImFont* font,ImFontBaked* baked,ImFontGlyph* glyph) +{ + return ImFontAtlasBakedDiscardFontGlyph(atlas,font,baked,glyph); +} +CIMGUI_API void igImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas,ImFontBaked* baked,ImFontConfig* src,ImFontGlyph* glyph,ImTextureRect* r,const unsigned char* src_pixels,ImTextureFormat src_fmt,int src_pitch) +{ + return ImFontAtlasBakedSetFontGlyphBitmap(atlas,baked,src,glyph,r,src_pixels,src_fmt,src_pitch); +} +CIMGUI_API void igImFontAtlasPackInit(ImFontAtlas* atlas) +{ + return ImFontAtlasPackInit(atlas); +} +CIMGUI_API ImFontAtlasRectId igImFontAtlasPackAddRect(ImFontAtlas* atlas,int w,int h,ImFontAtlasRectEntry* overwrite_entry) +{ + return ImFontAtlasPackAddRect(atlas,w,h,overwrite_entry); +} +CIMGUI_API ImTextureRect* igImFontAtlasPackGetRect(ImFontAtlas* atlas,ImFontAtlasRectId id) +{ + return ImFontAtlasPackGetRect(atlas,id); +} +CIMGUI_API ImTextureRect* igImFontAtlasPackGetRectSafe(ImFontAtlas* atlas,ImFontAtlasRectId id) +{ + return ImFontAtlasPackGetRectSafe(atlas,id); +} +CIMGUI_API void igImFontAtlasPackDiscardRect(ImFontAtlas* atlas,ImFontAtlasRectId id) +{ + return ImFontAtlasPackDiscardRect(atlas,id); +} +CIMGUI_API void igImFontAtlasUpdateNewFrame(ImFontAtlas* atlas,int frame_count,bool renderer_has_textures) +{ + return ImFontAtlasUpdateNewFrame(atlas,frame_count,renderer_has_textures); +} +CIMGUI_API void igImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas,ImDrawListSharedData* data) +{ + return ImFontAtlasAddDrawListSharedData(atlas,data); +} +CIMGUI_API void igImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas,ImDrawListSharedData* data) +{ + return ImFontAtlasRemoveDrawListSharedData(atlas,data); +} +CIMGUI_API void igImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas,ImTextureRef old_tex,ImTextureRef new_tex) +{ + return ImFontAtlasUpdateDrawListsTextures(atlas,old_tex,new_tex); +} +CIMGUI_API void igImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas) +{ + return ImFontAtlasUpdateDrawListsSharedData(atlas); +} +CIMGUI_API void igImFontAtlasTextureBlockConvert(const unsigned char* src_pixels,ImTextureFormat src_fmt,int src_pitch,unsigned char* dst_pixels,ImTextureFormat dst_fmt,int dst_pitch,int w,int h) +{ + return ImFontAtlasTextureBlockConvert(src_pixels,src_fmt,src_pitch,dst_pixels,dst_fmt,dst_pitch,w,h); +} +CIMGUI_API void igImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data) +{ + return ImFontAtlasTextureBlockPostProcess(data); +} +CIMGUI_API void igImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data,float multiply_factor) +{ + return ImFontAtlasTextureBlockPostProcessMultiply(data,multiply_factor); +} +CIMGUI_API void igImFontAtlasTextureBlockFill(ImTextureData* dst_tex,int dst_x,int dst_y,int w,int h,ImU32 col) +{ + return ImFontAtlasTextureBlockFill(dst_tex,dst_x,dst_y,w,h,col); +} +CIMGUI_API void igImFontAtlasTextureBlockCopy(ImTextureData* src_tex,int src_x,int src_y,ImTextureData* dst_tex,int dst_x,int dst_y,int w,int h) +{ + return ImFontAtlasTextureBlockCopy(src_tex,src_x,src_y,dst_tex,dst_x,dst_y,w,h); +} +CIMGUI_API void igImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas,ImTextureData* tex,int x,int y,int w,int h) +{ + return ImFontAtlasTextureBlockQueueUpload(atlas,tex,x,y,w,h); +} +CIMGUI_API int igImTextureDataGetFormatBytesPerPixel(ImTextureFormat format) +{ + return ImTextureDataGetFormatBytesPerPixel(format); +} +CIMGUI_API const char* igImTextureDataGetStatusName(ImTextureStatus status) +{ + return ImTextureDataGetStatusName(status); +} +CIMGUI_API const char* igImTextureDataGetFormatName(ImTextureFormat format) +{ + return ImTextureDataGetFormatName(format); +} +CIMGUI_API void igImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas) +{ + return ImFontAtlasDebugLogTextureRequests(atlas); +} +CIMGUI_API bool igImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas,ImGuiMouseCursor cursor_type,ImVec2* out_offset,ImVec2* out_size,ImVec2 out_uv_border[2],ImVec2 out_uv_fill[2]) +{ + return ImFontAtlasGetMouseCursorTexData(atlas,cursor_type,out_offset,out_size,out_uv_border,out_uv_fill); +} +#ifdef IMGUI_ENABLE_FREETYPE +CIMGUI_API const ImFontLoader* ImGuiFreeType_GetFontLoader() +{ + return ImGuiFreeType::GetFontLoader(); +} + +CIMGUI_API void ImGuiFreeType_SetAllocatorFunctions(void*(*alloc_func)(size_t sz,void* user_data),void(*free_func)(void* ptr,void* user_data),void* user_data) +{ + return ImGuiFreeType::SetAllocatorFunctions(alloc_func,free_func,user_data); +} + +CIMGUI_API bool ImGuiFreeType_DebugEditFontLoaderFlags(ImGuiFreeTypeLoaderFlags* p_font_loader_flags) +{ + return ImGuiFreeType::DebugEditFontLoaderFlags(p_font_loader_flags); +} + +#endif /////////////////////////////manual written functions -CIMGUI_API void igLogText(CONST char *fmt, ...) -{ - char buffer[256]; - va_list args; - va_start(args, fmt); - vsnprintf(buffer, 256, fmt, args); - va_end(args); - ImGui::LogText("%s", buffer); -} -CIMGUI_API void ImGuiTextBuffer_appendf(struct ImGuiTextBuffer *buffer, const char *fmt, ...) +CIMGUI_API void ImGuiTextBuffer_appendf(ImGuiTextBuffer *self, const char *fmt, ...) { va_list args; va_start(args, fmt); - buffer->appendfv(fmt, args); + self->appendfv(fmt, args); va_end(args); } @@ -5801,3 +6362,4 @@ CIMGUI_API void ImGuiPlatformIO_Set_Platform_GetWindowSize(ImGuiPlatformIO* plat } #endif + diff --git a/lib/third_party/imgui/imgui/include/imgui.h b/lib/third_party/imgui/imgui/include/imgui.h index e78f8086f..62b1899e3 100644 --- a/lib/third_party/imgui/imgui/include/imgui.h +++ b/lib/third_party/imgui/imgui/include/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9b +// dear imgui, v1.92.1 // (headers) // Help: @@ -28,18 +28,19 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.91.9b" -#define IMGUI_VERSION_NUM 19191 -#define IMGUI_HAS_TABLE -#define IMGUI_HAS_VIEWPORT // Viewport WIP branch -#define IMGUI_HAS_DOCK // Docking WIP branch +#define IMGUI_VERSION "1.92.1" +#define IMGUI_VERSION_NUM 19210 +#define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 +#define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 +#define IMGUI_HAS_VIEWPORT // In 'docking' WIP branch. +#define IMGUI_HAS_DOCK // In 'docking' WIP branch. /* Index of this file: // [SECTION] Header mess // [SECTION] Forward declarations and basic types -// [SECTION] Texture identifier (ImTextureID) +// [SECTION] Texture identifiers (ImTextureID, ImTextureRef) // [SECTION] Dear ImGui end-user API functions // [SECTION] Flags & Enumerations // [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) @@ -50,7 +51,8 @@ Index of this file: // [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) // [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO, ImGuiSelectionRequest, ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage) // [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) -// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) +// [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) +// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFontBaked, ImFont) // [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) // [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformMonitor, ImGuiPlatformImeData) // [SECTION] Obsolete functions and types @@ -171,10 +173,15 @@ struct ImDrawListSplitter; // Helper to split a draw list into differen struct ImDrawVert; // A single vertex (pos + uv + col = 20 bytes by default. Override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) struct ImFont; // Runtime data for a single font within a parent ImFontAtlas struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader -struct ImFontBuilderIO; // Opaque interface to a font builder (stb_truetype or FreeType). +struct ImFontAtlasBuilder; // Opaque storage for building a ImFontAtlas +struct ImFontAtlasRect; // Output of ImFontAtlas::GetCustomRect() when using custom rectangles. +struct ImFontBaked; // Baked data for a ImFont at a given size. struct ImFontConfig; // Configuration data when adding a font or merging fonts struct ImFontGlyph; // A single font glyph (code point + coordinates within in ImFontAtlas + offset) struct ImFontGlyphRangesBuilder; // Helper to build glyph ranges from text/string data +struct ImFontLoader; // Opaque interface to a font loading backend (stb_truetype, FreeType etc.). +struct ImTextureData; // Specs and pixel storage for a texture used by Dear ImGui. +struct ImTextureRect; // Coordinates of a rectangle within a texture. struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 (*OBSOLETE* please avoid using) // Forward declarations: ImGui layer @@ -228,7 +235,8 @@ typedef int ImGuiTableBgTarget; // -> enum ImGuiTableBgTarget_ // Enum: A // - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments. typedef int ImDrawFlags; // -> enum ImDrawFlags_ // Flags: for ImDrawList functions typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList instance -typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas build +typedef int ImFontFlags; // -> enum ImFontFlags_ // Flags: for ImFont +typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for InvisibleButton() typedef int ImGuiChildFlags; // -> enum ImGuiChildFlags_ // Flags: for BeginChild() @@ -306,18 +314,65 @@ struct ImVec4 IM_MSVC_RUNTIME_CHECKS_RESTORE //----------------------------------------------------------------------------- -// [SECTION] Texture identifier (ImTextureID) +// [SECTION] Texture identifiers (ImTextureID, ImTextureRef) //----------------------------------------------------------------------------- -// ImTexture: user data for renderer backend to identify a texture [Compile-time configurable type] -// - To use something else than an opaque void* pointer: override with e.g. '#define ImTextureID MyTextureType*' in your imconfig.h file. -// - This can be whatever to you want it to be! read the FAQ about ImTextureID for details. -// - You can make this a structure with various constructors if you need. You will have to implement ==/!= operators. -// - (note: before v1.91.4 (2024/10/08) the default type for ImTextureID was void*. Use intermediary intptr_t cast and read FAQ if you have casting warnings) +// ImTextureID = backend specific, low-level identifier for a texture uploaded in GPU/graphics system. +// [Compile-time configurable type] +// - When a Rendered Backend creates a texture, it store its native identifier into a ImTextureID value. +// (e.g. Used by DX11 backend to a `ID3D11ShaderResourceView*`; Used by OpenGL backends to store `GLuint`; +// Used by SDLGPU backend to store a `SDL_GPUTextureSamplerBinding*`, etc.). +// - User may submit their own textures to e.g. ImGui::Image() function by passing the same type. +// - During the rendering loop, the Renderer Backend retrieve the ImTextureID, which stored inside a +// ImTextureRef, which is stored inside a ImDrawCmd. +// - Compile-time type configuration: +// - To use something other than a 64-bit value: add '#define ImTextureID MyTextureType*' in your imconfig.h file. +// - This can be whatever to you want it to be! read the FAQ entry about textures for details. +// - You may decide to store a higher-level structure containing texture, sampler, shader etc. with various +// constructors if you like. You will need to implement ==/!= operators. +// History: +// - In v1.91.4 (2024/10/08): the default type for ImTextureID was changed from 'void*' to 'ImU64'. This allowed backends requirig 64-bit worth of data to build on 32-bit architectures. Use intermediary intptr_t cast and read FAQ if you have casting warnings. +// - In v1.92.0 (2025/06/11): added ImTextureRef which carry either a ImTextureID either a pointer to internal texture atlas. All user facing functions taking ImTextureID changed to ImTextureRef #ifndef ImTextureID -typedef ImU64 ImTextureID; // Default: store a pointer or an integer fitting in a pointer (most renderer backends are ok with that) +typedef ImU64 ImTextureID; // Default: store up to 64-bits (any pointer or integer). A majority of backends are ok with that. #endif +// Define this if you need 0 to be a valid ImTextureID for your backend. +#ifndef ImTextureID_Invalid +#define ImTextureID_Invalid ((ImTextureID)0) +#endif + +// ImTextureRef = higher-level identifier for a texture. +// The identifier is valid even before the texture has been uploaded to the GPU/graphics system. +// This is what gets passed to functions such as `ImGui::Image()`, `ImDrawList::AddImage()`. +// This is what gets stored in draw commands (`ImDrawCmd`) to identify a texture during rendering. +// - When a texture is created by user code (e.g. custom images), we directly stores the low-level ImTextureID. +// - When a texture is created by the backend, we stores a ImTextureData* which becomes an indirection +// to extract the ImTextureID value during rendering, after texture upload has happened. +// - There is no constructor to create a ImTextureID from a ImTextureData* as we don't expect this +// to be useful to the end-user, and it would be erroneously called by many legacy code. +// - If you want to bind the current atlas when using custom rectangle, you can use io.Fonts->TexRef. +// - Binding generators for languages such as C (which don't have constructors), should provide a helper, e.g. +// inline ImTextureRef ImTextureRefFromID(ImTextureID tex_id) { ImTextureRef tex_ref = { ._TexData = NULL, .TexID = tex_id }; return tex_ref; } +// In 1.92 we changed most drawing functions using ImTextureID to use ImTextureRef. +// We intentionally do not provide an implicit ImTextureRef -> ImTextureID cast operator because it is technically lossy to convert ImTextureRef to ImTextureID before rendering. +IM_MSVC_RUNTIME_CHECKS_OFF +struct ImTextureRef +{ + ImTextureRef() { _TexData = NULL; _TexID = ImTextureID_Invalid; } + ImTextureRef(ImTextureID tex_id) { _TexData = NULL; _TexID = tex_id; } +#if !defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && !defined(ImTextureID) + ImTextureRef(void* tex_id) { _TexData = NULL; _TexID = (ImTextureID)(size_t)tex_id; } // For legacy backends casting to ImTextureID +#endif + + inline ImTextureID GetTexID() const; // == (_TexData ? _TexData->TexID : _TexID) // Implemented below in the file. + + // Members (either are set, never both!) + ImTextureData* _TexData; // A texture, generally owned by a ImFontAtlas. Will convert to ImTextureID during render loop, after texture has been uploaded. + ImTextureID _TexID; // _OR_ Low-level backend texture identifier, if already uploaded or created by user/app. Generally provided to e.g. ImGui::Image() calls. +}; +IM_MSVC_RUNTIME_CHECKS_RESTORE + //----------------------------------------------------------------------------- // [SECTION] Dear ImGui end-user API functions // (Note that ImGui:: being a namespace, you can add extra ImGui:: functions in your own separate file. Please don't modify imgui source files!) @@ -341,7 +396,7 @@ namespace ImGui IMGUI_API void NewFrame(); // start a new Dear ImGui frame, you can submit any command from this point until Render()/EndFrame(). IMGUI_API void EndFrame(); // ends the Dear ImGui frame. automatically called by Render(). If you don't need to render data (skipping rendering) you may call EndFrame() without Render()... but you'll have wasted CPU already! If you don't need to render, better to not create any windows and not call NewFrame() at all! IMGUI_API void Render(); // ends the Dear ImGui frame, finalize the draw data. You can then get call GetDrawData(). - IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). this is what you have to render. + IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). Call ImGui_ImplXXXX_RenderDrawData() function in your Renderer Backend to render. // Demo, Debug, Information IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create Demo window. demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! @@ -426,7 +481,6 @@ namespace ImGui IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0, 0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / top-most. prefer using SetNextWindowFocus(). - IMGUI_API void SetWindowFontScale(float scale); // [OBSOLETE] set font scale. Adjust IO.FontGlobalScale if you want to scale all windows. This is an old API! For correct scaling, prefer to reload font + rebuild ImFontAtlas + call style.ScaleAllSizes(). IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position. IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state @@ -446,9 +500,29 @@ namespace ImGui IMGUI_API void SetScrollFromPosX(float local_x, float center_x_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. - // Parameters stacks (shared) - IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font + // Parameters stacks (font) + // - PushFont(font, 0.0f) // Change font and keep current size + // - PushFont(NULL, 20.0f) // Keep font and change current size + // - PushFont(font, 20.0f) // Change font and set size to 20.0f + // - PushFont(font, style.FontSizeBase * 2.0f) // Change font and set size to be twice bigger than current size. + // - PushFont(font, font->LegacySize) // Change font and set size to size passed to AddFontXXX() function. Same as pre-1.92 behavior. + // *IMPORTANT* before 1.92, fonts had a single size. They can now be dynamically be adjusted. + // - In 1.92 we have REMOVED the single parameter version of PushFont() because it seems like the easiest way to provide an error-proof transition. + // - PushFont(font) before 1.92 = PushFont(font, font->LegacySize) after 1.92 // Use default font size as passed to AddFontXXX() function. + // *IMPORTANT* global scale factors are applied over the provided size. + // - Global scale factors are: 'style.FontScaleMain', 'style.FontScaleDpi' and maybe more. + // - If you want to apply a factor to the _current_ font size: + // - CORRECT: PushFont(NULL, style.FontSizeBase) // use current unscaled size == does nothing + // - CORRECT: PushFont(NULL, style.FontSizeBase * 2.0f) // use current unscaled size x2 == make text twice bigger + // - INCORRECT: PushFont(NULL, GetFontSize()) // INCORRECT! using size after global factors already applied == GLOBAL SCALING FACTORS WILL APPLY TWICE! + // - INCORRECT: PushFont(NULL, GetFontSize() * 2.0f) // INCORRECT! using size after global factors already applied == GLOBAL SCALING FACTORS WILL APPLY TWICE! + IMGUI_API void PushFont(ImFont* font, float font_size_base_unscaled); // Use NULL as a shortcut to keep current font. Use 0.0f to keep current size. IMGUI_API void PopFont(); + IMGUI_API ImFont* GetFont(); // get current font + IMGUI_API float GetFontSize(); // get current scaled font size (= height in pixels). AFTER global scale factors applied. *IMPORTANT* DO NOT PASS THIS VALUE TO PushFont()! Use ImGui::GetStyle().FontSizeBase to get value before global scale factors. + IMGUI_API ImFontBaked* GetFontBaked(); // get current font bound at current size // == GetFont()->GetFontBaked(GetFontSize()) + + // Parameters stacks (shared) IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col); // modify a style color. always use this if you modify the style after NewFrame(). IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); IMGUI_API void PopStyleColor(int count = 1); @@ -470,8 +544,6 @@ namespace ImGui // Style read access // - Use the ShowStyleEditor() function to interactively see/edit the colors. - IMGUI_API ImFont* GetFont(); // get current font - IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a white pixel, useful to draw custom shapes via the ImDrawList API IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier, packed as a 32-bit value suitable for ImDrawList IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList @@ -567,16 +639,17 @@ namespace ImGui IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-FLT_MIN, 0), const char* overlay = NULL); IMGUI_API void Bullet(); // draw a small circle + keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses IMGUI_API bool TextLink(const char* label); // hyperlink text button, return true when clicked - IMGUI_API void TextLinkOpenURL(const char* label, const char* url = NULL); // hyperlink text button, automatically open file/url when clicked + IMGUI_API bool TextLinkOpenURL(const char* label, const char* url = NULL); // hyperlink text button, automatically open file/url when clicked // Widgets: Images - // - Read about ImTextureID here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples + // - Read about ImTextureID/ImTextureRef here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples // - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above. // - Image() pads adds style.ImageBorderSize on each side, ImageButton() adds style.FramePadding on each side. // - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified. - IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1)); - IMGUI_API void ImageWithBg(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); - IMGUI_API bool ImageButton(const char* str_id, ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); + // - An obsolete version of Image(), before 1.91.9 (March 2025), had a 'tint_col' parameter which is now supported by the ImageWithBg() function. + IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1)); + IMGUI_API void ImageWithBg(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); + IMGUI_API bool ImageButton(const char* str_id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); // Widgets: Combo Box (Dropdown) // - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items. @@ -704,7 +777,7 @@ namespace ImGui // - This is essentially a thin wrapper to using BeginChild/EndChild with the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label. // - If you don't need a label you can probably simply use BeginChild() with the ImGuiChildFlags_FrameStyle flag for the same result. // - You can submit contents and manage your selection state however you want it, by creating e.g. Selectable() or any other items. - // - The simplified/old ListBox() api are helpers over BeginListBox()/EndListBox() which are kept available for convenience purpose. This is analoguous to how Combos are created. + // - The simplified/old ListBox() api are helpers over BeginListBox()/EndListBox() which are kept available for convenience purpose. This is analogous to how Combos are created. // - Choose frame width: size.x > 0.0f: custom / size.x < 0.0f or -FLT_MIN: right-align / size.x = 0.0f (default): use current ItemWidth // - Choose frame height: size.y > 0.0f: custom / size.y < 0.0f or -FLT_MIN: bottom-align / size.y = 0.0f (default): arbitrary default height which can fit ~7 items IMGUI_API bool BeginListBox(const char* label, const ImVec2& size = ImVec2(0, 0)); // open a framed scrolling region @@ -1050,7 +1123,7 @@ namespace ImGui IMGUI_API void ResetMouseDragDelta(ImGuiMouseButton button = 0); // IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired mouse cursor shape. Important: reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you IMGUI_API void SetMouseCursor(ImGuiMouseCursor cursor_type); // set desired mouse cursor shape - IMGUI_API void SetNextFrameWantCaptureMouse(bool want_capture_mouse); // Override io.WantCaptureMouse flag next frame (said flag is left for your application to handle, typical when true it instucts your app to ignore inputs). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse;" after the next NewFrame() call. + IMGUI_API void SetNextFrameWantCaptureMouse(bool want_capture_mouse); // Override io.WantCaptureMouse flag next frame (said flag is left for your application to handle, typical when true it instructs your app to ignore inputs). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse;" after the next NewFrame() call. // Clipboard Utilities // - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard. @@ -1250,12 +1323,19 @@ enum ImGuiTreeNodeFlags_ ImGuiTreeNodeFlags_SpanAllColumns = 1 << 14, // Frame will span all columns of its container table (label will still fit in current column) ImGuiTreeNodeFlags_LabelSpanAllColumns = 1 << 15, // Label will span all columns of its container table //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 16, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible - ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 17, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop) + ImGuiTreeNodeFlags_NavLeftJumpsToParent = 1 << 17, // Nav: left arrow moves back to parent. This is processed in TreePop() when there's an unfullfilled Left nav request remaining. ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog, + // [EXPERIMENTAL] Draw lines connecting TreeNode hierarchy. Discuss in GitHub issue #2920. + // Default value is pulled from style.TreeLinesFlags. May be overridden in TreeNode calls. + ImGuiTreeNodeFlags_DrawLinesNone = 1 << 18, // No lines drawn + ImGuiTreeNodeFlags_DrawLinesFull = 1 << 19, // Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. Faster (for large trees). + ImGuiTreeNodeFlags_DrawLinesToNodes = 1 << 20, // Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. Slower (for large trees). + #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiTreeNodeFlags_AllowItemOverlap = ImGuiTreeNodeFlags_AllowOverlap, // Renamed in 1.89.7 - ImGuiTreeNodeFlags_SpanTextWidth = ImGuiTreeNodeFlags_SpanLabelWidth,// Renamed in 1.90.7 + ImGuiTreeNodeFlags_NavLeftJumpsBackHere = ImGuiTreeNodeFlags_NavLeftJumpsToParent, // Renamed in 1.92.0 + ImGuiTreeNodeFlags_SpanTextWidth = ImGuiTreeNodeFlags_SpanLabelWidth, // Renamed in 1.90.7 + ImGuiTreeNodeFlags_AllowItemOverlap = ImGuiTreeNodeFlags_AllowOverlap, // Renamed in 1.89.7 #endif }; @@ -1513,7 +1593,7 @@ enum ImGuiKey : int ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, - ImGuiKey_LeftCtrl, ImGuiKey_LeftShift, ImGuiKey_LeftAlt, ImGuiKey_LeftSuper, + ImGuiKey_LeftCtrl, ImGuiKey_LeftShift, ImGuiKey_LeftAlt, ImGuiKey_LeftSuper, // Also see ImGuiMod_Ctrl, ImGuiMod_Shift, ImGuiMod_Alt, ImGuiMod_Super below! ImGuiKey_RightCtrl, ImGuiKey_RightShift, ImGuiKey_RightAlt, ImGuiKey_RightSuper, ImGuiKey_Menu, ImGuiKey_0, ImGuiKey_1, ImGuiKey_2, ImGuiKey_3, ImGuiKey_4, ImGuiKey_5, ImGuiKey_6, ImGuiKey_7, ImGuiKey_8, ImGuiKey_9, @@ -1553,32 +1633,34 @@ enum ImGuiKey : int ImGuiKey_AppForward, ImGuiKey_Oem102, // Non-US backslash. - // Gamepad (some of those are analog values, 0.0f to 1.0f) // NAVIGATION ACTION + // Gamepad + // (analog values are 0.0f to 1.0f) // (download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets) - ImGuiKey_GamepadStart, // Menu (Xbox) + (Switch) Start/Options (PS) - ImGuiKey_GamepadBack, // View (Xbox) - (Switch) Share (PS) - ImGuiKey_GamepadFaceLeft, // X (Xbox) Y (Switch) Square (PS) // Tap: Toggle Menu. Hold: Windowing mode (Focus/Move/Resize windows) - ImGuiKey_GamepadFaceRight, // B (Xbox) A (Switch) Circle (PS) // Cancel / Close / Exit - ImGuiKey_GamepadFaceUp, // Y (Xbox) X (Switch) Triangle (PS) // Text Input / On-screen Keyboard - ImGuiKey_GamepadFaceDown, // A (Xbox) B (Switch) Cross (PS) // Activate / Open / Toggle / Tweak - ImGuiKey_GamepadDpadLeft, // D-pad Left // Move / Tweak / Resize Window (in Windowing mode) - ImGuiKey_GamepadDpadRight, // D-pad Right // Move / Tweak / Resize Window (in Windowing mode) - ImGuiKey_GamepadDpadUp, // D-pad Up // Move / Tweak / Resize Window (in Windowing mode) - ImGuiKey_GamepadDpadDown, // D-pad Down // Move / Tweak / Resize Window (in Windowing mode) - ImGuiKey_GamepadL1, // L Bumper (Xbox) L (Switch) L1 (PS) // Tweak Slower / Focus Previous (in Windowing mode) - ImGuiKey_GamepadR1, // R Bumper (Xbox) R (Switch) R1 (PS) // Tweak Faster / Focus Next (in Windowing mode) - ImGuiKey_GamepadL2, // L Trig. (Xbox) ZL (Switch) L2 (PS) [Analog] - ImGuiKey_GamepadR2, // R Trig. (Xbox) ZR (Switch) R2 (PS) [Analog] - ImGuiKey_GamepadL3, // L Stick (Xbox) L3 (Switch) L3 (PS) - ImGuiKey_GamepadR3, // R Stick (Xbox) R3 (Switch) R3 (PS) - ImGuiKey_GamepadLStickLeft, // [Analog] // Move Window (in Windowing mode) - ImGuiKey_GamepadLStickRight, // [Analog] // Move Window (in Windowing mode) - ImGuiKey_GamepadLStickUp, // [Analog] // Move Window (in Windowing mode) - ImGuiKey_GamepadLStickDown, // [Analog] // Move Window (in Windowing mode) - ImGuiKey_GamepadRStickLeft, // [Analog] - ImGuiKey_GamepadRStickRight, // [Analog] - ImGuiKey_GamepadRStickUp, // [Analog] - ImGuiKey_GamepadRStickDown, // [Analog] + // // XBOX | SWITCH | PLAYSTA. | -> ACTION + ImGuiKey_GamepadStart, // Menu | + | Options | + ImGuiKey_GamepadBack, // View | - | Share | + ImGuiKey_GamepadFaceLeft, // X | Y | Square | Tap: Toggle Menu. Hold: Windowing mode (Focus/Move/Resize windows) + ImGuiKey_GamepadFaceRight, // B | A | Circle | Cancel / Close / Exit + ImGuiKey_GamepadFaceUp, // Y | X | Triangle | Text Input / On-screen Keyboard + ImGuiKey_GamepadFaceDown, // A | B | Cross | Activate / Open / Toggle / Tweak + ImGuiKey_GamepadDpadLeft, // D-pad Left | " | " | Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadDpadRight, // D-pad Right | " | " | Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadDpadUp, // D-pad Up | " | " | Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadDpadDown, // D-pad Down | " | " | Move / Tweak / Resize Window (in Windowing mode) + ImGuiKey_GamepadL1, // L Bumper | L | L1 | Tweak Slower / Focus Previous (in Windowing mode) + ImGuiKey_GamepadR1, // R Bumper | R | R1 | Tweak Faster / Focus Next (in Windowing mode) + ImGuiKey_GamepadL2, // L Trigger | ZL | L2 | [Analog] + ImGuiKey_GamepadR2, // R Trigger | ZR | R2 | [Analog] + ImGuiKey_GamepadL3, // L Stick | L3 | L3 | + ImGuiKey_GamepadR3, // R Stick | R3 | R3 | + ImGuiKey_GamepadLStickLeft, // | | | [Analog] Move Window (in Windowing mode) + ImGuiKey_GamepadLStickRight, // | | | [Analog] Move Window (in Windowing mode) + ImGuiKey_GamepadLStickUp, // | | | [Analog] Move Window (in Windowing mode) + ImGuiKey_GamepadLStickDown, // | | | [Analog] Move Window (in Windowing mode) + ImGuiKey_GamepadRStickLeft, // | | | [Analog] + ImGuiKey_GamepadRStickRight, // | | | [Analog] + ImGuiKey_GamepadRStickUp, // | | | [Analog] + ImGuiKey_GamepadRStickDown, // | | | [Analog] // Aliases: Mouse Buttons (auto-submitted from AddMouseButtonEvent() calls) // - This is mirroring the data also written to io.MouseDown[], io.MouseWheel, in a format allowing them to be accessed via standard key API. @@ -1586,11 +1668,15 @@ enum ImGuiKey : int // [Internal] Reserved for mod storage ImGuiKey_ReservedForModCtrl, ImGuiKey_ReservedForModShift, ImGuiKey_ReservedForModAlt, ImGuiKey_ReservedForModSuper, + + // [Internal] If you need to iterate all keys (for e.g. an input mapper) you may use ImGuiKey_NamedKey_BEGIN..ImGuiKey_NamedKey_END. ImGuiKey_NamedKey_END, + ImGuiKey_NamedKey_COUNT = ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN, // Keyboard Modifiers (explicitly submitted by backend via AddKeyEvent() calls) - // - This is mirroring the data also written to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper, in a format allowing - // them to be accessed via standard key API, allowing calls such as IsKeyPressed(), IsKeyReleased(), querying duration etc. + // - Any functions taking a ImGuiKeyChord parameter can binary-or those with regular keys, e.g. Shortcut(ImGuiMod_Ctrl | ImGuiKey_S). + // - Those are written back into io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper for convenience, + // but may be accessed via standard key API such as IsKeyPressed(), IsKeyReleased(), querying duration etc. // - Code polling every key (e.g. an interface to detect a key press for input mapping) might want to ignore those // and prefer using the real keys (e.g. ImGuiKey_LeftCtrl, ImGuiKey_RightCtrl instead of ImGuiMod_Ctrl). // - In theory the value of keyboard modifiers should be roughly equivalent to a logical or of the equivalent left/right keys. @@ -1604,11 +1690,6 @@ enum ImGuiKey : int ImGuiMod_Super = 1 << 15, // Windows/Super (non-macOS), Ctrl (macOS) ImGuiMod_Mask_ = 0xF000, // 4-bits - // [Internal] If you need to iterate all keys (for e.g. an input mapper) you may use ImGuiKey_NamedKey_BEGIN..ImGuiKey_NamedKey_END. - ImGuiKey_NamedKey_COUNT = ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN, - //ImGuiKey_KeysData_SIZE = ImGuiKey_NamedKey_COUNT, // Size of KeysData[]: only hold named keys - //ImGuiKey_KeysData_OFFSET = ImGuiKey_NamedKey_BEGIN, // Accesses to io.KeysData[] must use (key - ImGuiKey_NamedKey_BEGIN) index. - #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiKey_COUNT = ImGuiKey_NamedKey_END, // Obsoleted in 1.91.5 because it was extremely misleading (since named keys don't start at 0 anymore) ImGuiMod_Shortcut = ImGuiMod_Ctrl, // Removed in 1.90.7, you can now simply use ImGuiMod_Ctrl @@ -1658,8 +1739,6 @@ enum ImGuiConfigFlags_ // [BETA] Viewports // When using viewports it is recommended that your default value for ImGuiCol_WindowBg is opaque (Alpha=1.0) so transition to a viewport won't be noticeable. ImGuiConfigFlags_ViewportsEnable = 1 << 10, // Viewport enable flags (require both ImGuiBackendFlags_PlatformHasViewports + ImGuiBackendFlags_RendererHasViewports set by the respective backends) - ImGuiConfigFlags_DpiEnableScaleViewports= 1 << 14, // [BETA: Don't use] FIXME-DPI: Reposition and resize imgui windows when the DpiScale of a viewport changed (mostly useful for the main viewport hosting other window). Note that resizing the main window itself is up to your application. - ImGuiConfigFlags_DpiEnableScaleFonts = 1 << 15, // [BETA: Don't use] FIXME-DPI: Request bitmap-scaled fonts to match DpiScale. This is a very low-quality workaround. The correct way to handle DPI is _currently_ to replace the atlas and/or fonts in the Platform_OnChangedViewport callback, but this is all early work in progress. // User storage (to allow your backend/engine to communicate to code that may be shared between multiple projects. Those flags are NOT used by core Dear ImGui) ImGuiConfigFlags_IsSRGB = 1 << 20, // Application is SRGB-aware. @@ -1668,6 +1747,8 @@ enum ImGuiConfigFlags_ #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, // [moved/renamed in 1.91.4] -> use bool io.ConfigNavMoveSetMousePos ImGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3, // [moved/renamed in 1.91.4] -> use bool io.ConfigNavCaptureKeyboard + ImGuiConfigFlags_DpiEnableScaleFonts = 1 << 14, // [moved/renamed in 1.92.0] -> use bool io.ConfigDpiScaleFonts + ImGuiConfigFlags_DpiEnableScaleViewports= 1 << 15, // [moved/renamed in 1.92.0] -> use bool io.ConfigDpiScaleViewports #endif }; @@ -1679,6 +1760,7 @@ enum ImGuiBackendFlags_ ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape. ImGuiBackendFlags_HasSetMousePos = 1 << 2, // Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if io.ConfigNavMoveSetMousePos is set). ImGuiBackendFlags_RendererHasVtxOffset = 1 << 3, // Backend Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices. + ImGuiBackendFlags_RendererHasTextures = 1 << 4, // Backend Renderer supports ImTextureData requests to create/update/destroy textures. This enables incremental texture updates and texture reloads. See https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for instructions on how to upgrade your custom backend. // [BETA] Viewports ImGuiBackendFlags_PlatformHasViewports = 1 << 10, // Backend Platform supports multiple viewports. @@ -1722,6 +1804,7 @@ enum ImGuiCol_ ImGuiCol_ResizeGrip, // Resize grip in lower-right and lower-left corners of windows. ImGuiCol_ResizeGripHovered, ImGuiCol_ResizeGripActive, + ImGuiCol_InputTextCursor, // InputText cursor/caret ImGuiCol_TabHovered, // Tab background, when hovered ImGuiCol_Tab, // Tab background, when tab-bar is focused & tab is unselected ImGuiCol_TabSelected, // Tab background, when tab-bar is focused & tab is selected @@ -1741,7 +1824,8 @@ enum ImGuiCol_ ImGuiCol_TableRowBg, // Table row background (even rows) ImGuiCol_TableRowBgAlt, // Table row background (odd rows) ImGuiCol_TextLink, // Hyperlink color - ImGuiCol_TextSelectedBg, + ImGuiCol_TextSelectedBg, // Selected text inside an InputText + ImGuiCol_TreeLines, // Tree node hierarchy outlines when using ImGuiTreeNodeFlags_DrawLines ImGuiCol_DragDropTarget, // Rectangle highlighting a drop target ImGuiCol_NavCursor, // Color of keyboard/gamepad navigation cursor/rectangle, when visible ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB @@ -1798,6 +1882,8 @@ enum ImGuiStyleVar_ ImGuiStyleVar_TabBarOverlineSize, // float TabBarOverlineSize ImGuiStyleVar_TableAngledHeadersAngle, // float TableAngledHeadersAngle ImGuiStyleVar_TableAngledHeadersTextAlign,// ImVec2 TableAngledHeadersTextAlign + ImGuiStyleVar_TreeLinesSize, // float TreeLinesSize + ImGuiStyleVar_TreeLinesRounding, // float TreeLinesRounding ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign ImGuiStyleVar_SeparatorTextBorderSize, // float SeparatorTextBorderSize @@ -2222,6 +2308,12 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE struct ImGuiStyle { + // Font scaling + // - recap: ImGui::GetFontSize() == FontSizeBase * (FontScaleMain * FontScaleDpi * other_scaling_factors) + float FontSizeBase; // Current base font size before external global factors are applied. Use PushFont(NULL, size) to modify. Use ImGui::GetFontSize() to obtain scaled value. + float FontScaleMain; // Main global scale factor. May be set by application once, or exposed to end-user. + float FontScaleDpi; // Additional global scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. + float Alpha; // Global alpha applies to everything in Dear ImGui. float DisabledAlpha; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. ImVec2 WindowPadding; // Padding within a window. @@ -2258,6 +2350,9 @@ struct ImGuiStyle float TabBarOverlineSize; // Thickness of tab-bar overline, which highlights the selected tab-bar. float TableAngledHeadersAngle; // Angle of angled headers (supported values range from -50.0f degrees to +50.0f degrees). ImVec2 TableAngledHeadersTextAlign;// Alignment of angled headers within the cell + ImGuiTreeNodeFlags TreeLinesFlags; // Default way to draw lines connecting TreeNode hierarchy. ImGuiTreeNodeFlags_DrawLinesNone or ImGuiTreeNodeFlags_DrawLinesFull or ImGuiTreeNodeFlags_DrawLinesToNodes. + float TreeLinesSize; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines. + float TreeLinesRounding; // Radius of lines connecting child nodes to the vertical line. ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. @@ -2289,8 +2384,13 @@ struct ImGuiStyle ImGuiHoveredFlags HoverFlagsForTooltipMouse;// Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse. ImGuiHoveredFlags HoverFlagsForTooltipNav; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad. - IMGUI_API ImGuiStyle(); - IMGUI_API void ScaleAllSizes(float scale_factor); + // [Internal] + float _MainScale; // FIXME-WIP: Reference scale, as applied by ScaleAllSizes(). + float _NextFrameFontSizeBase; // FIXME: Temporary hack until we finish remaining work. + + // Functions + IMGUI_API ImGuiStyle(); + IMGUI_API void ScaleAllSizes(float scale_factor); // Scale all spacing/padding/thickness values. Do not scale fonts. // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS @@ -2328,7 +2428,8 @@ struct ImGuiIO ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Keyboard/Gamepad navigation options, etc. ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by backend (imgui_impl_xxx files or custom backend) to communicate features supported by the backend. - ImVec2 DisplaySize; // // Main display size, in pixels (generally == GetMainViewport()->Size). May change every frame. + ImVec2 DisplaySize; // // Main display size, in pixels (== GetMainViewport()->Size). May change every frame. + ImVec2 DisplayFramebufferScale; // = (1, 1) // Main display density. For retina display where window coordinates are different from framebuffer coordinates. This will affect font density + will end up in ImDrawData::FramebufferScale. float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. May change every frame. float IniSavingRate; // = 5.0f // Minimum time between saving positions/sizes to .ini file, in seconds. const char* IniFilename; // = "imgui.ini" // Path to .ini file (important: default "imgui.ini" is relative to current working dir!). Set NULL to disable automatic .ini loading/saving or if you want to manually call LoadIniSettingsXXX() / SaveIniSettingsXXX() functions. @@ -2337,10 +2438,8 @@ struct ImGuiIO // Font system ImFontAtlas*Fonts; // // Font atlas: load, rasterize and pack one or more fonts into a single texture. - float FontGlobalScale; // = 1.0f // Global scale all fonts - bool FontAllowUserScaling; // = false // [OBSOLETE] Allow user scaling text of individual window with CTRL+Wheel. ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. - ImVec2 DisplayFramebufferScale; // = (1, 1) // For retina display or other situations where window coordinates are different from framebuffer coordinates. This generally ends up in ImDrawData::FramebufferScale. + bool FontAllowUserScaling; // = false // [OBSOLETE] Allow user scaling text of individual window with CTRL+Wheel. // Keyboard/Gamepad Navigation options bool ConfigNavSwapGamepadButtons; // = false // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout. @@ -2363,6 +2462,11 @@ struct ImGuiIO bool ConfigViewportsNoDecoration; // = true // Disable default OS window decoration flag for secondary viewports. When a viewport doesn't want window decorations, ImGuiViewportFlags_NoDecoration will be set on it. Enabling decoration can create subsequent issues at OS levels (e.g. minimum window size). bool ConfigViewportsNoDefaultParent; // = false // Disable default OS parenting to main viewport for secondary viewports. By default, viewports are marked with ParentViewportId = , expecting the platform backend to setup a parent/child relationship between the OS windows (some backend may ignore this). Set to true if you want the default to be 0, then all viewports will be top-level OS windows. + // DPI/Scaling options + // This may keep evolving during 1.92.x releases. Expect some turbulence. + bool ConfigDpiScaleFonts; // = false // [EXPERIMENTAL] Automatically overwrite style.FontScaleDpi when Monitor DPI changes. This will scale fonts but _NOT_ scale sizes/padding for now. + bool ConfigDpiScaleViewports; // = false // [EXPERIMENTAL] Scale Dear ImGui and Platform Windows when Monitor DPI changes. + // Miscellaneous options // (you can visualize and interact with all options in 'Demo->Configuration') bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations. @@ -2517,7 +2621,7 @@ struct ImGuiIO // Other state maintained from data above + IO function calls ImGuiKeyChord KeyMods; // Key mods flags (any of ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Alt/ImGuiMod_Super flags, same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags. Read-only, updated by NewFrame() - ImGuiKeyData KeysData[ImGuiKey_NamedKey_COUNT];// Key state for all known keys. Use IsKeyXXX() functions to access this. + ImGuiKeyData KeysData[ImGuiKey_NamedKey_COUNT];// Key state for all known keys. MUST use 'key - ImGuiKey_NamedKey_BEGIN' as index. Use IsKeyXXX() functions to access this. bool WantCaptureMouseUnlessPopupClose; // Alternative to WantCaptureMouse: (WantCaptureMouse == true && WantCaptureMouseUnlessPopupClose == false) when a click over void is expected to close a popup. ImVec2 MousePosPrev; // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid) ImVec2 MouseClickedPos[5]; // Position at time of clicking @@ -2552,9 +2656,11 @@ struct ImGuiIO //float NavInputs[ImGuiNavInput_COUNT]; // [LEGACY] Since 1.88, NavInputs[] was removed. Backends from 1.60 to 1.86 won't build. Feed gamepad inputs via io.AddKeyEvent() and ImGuiKey_GamepadXXX enums. //void* ImeWindowHandle; // [Obsoleted in 1.87] Set ImGuiViewport::PlatformHandleRaw instead. Set this to your HWND to get automatic IME cursor positioning. +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + float FontGlobalScale; // Moved io.FontGlobalScale to style.FontScaleMain in 1.92 (June 2025) + // Legacy: before 1.91.1, clipboard functions were stored in ImGuiIO instead of ImGuiPlatformIO. // As this is will affect all users of custom engines/backends, we are providing proper legacy redirection (will obsolete). -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS const char* (*GetClipboardTextFn)(void* user_data); void (*SetClipboardTextFn)(void* user_data, const char* text); void* ClipboardUserData; @@ -2813,7 +2919,7 @@ struct ImGuiListClipper int DisplayEnd; // End of items to display (exclusive) int ItemsCount; // [Internal] Number of items float ItemsHeight; // [Internal] Height of item after a first step and item submission can calculate it - float StartPosY; // [Internal] Cursor position at the time of Begin() or after table frozen rows are all processed + double StartPosY; // [Internal] Cursor position at the time of Begin() or after table frozen rows are all processed double StartSeekOffsetY; // [Internal] Account for frozen rows in a table and initial loss of precision in very large windows. void* TempData; // [Internal] Internal data @@ -2837,7 +2943,7 @@ struct ImGuiListClipper #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS inline void IncludeRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.9] - inline void ForceDisplayRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.6] + //inline void ForceDisplayRangeByIndices(int item_begin, int item_end) { IncludeItemsByIndex(item_begin, item_end); } // [renamed in 1.89.6] //inline ImGuiListClipper(int items_count, float items_height = -1.0f) { memset(this, 0, sizeof(*this)); ItemsCount = -1; Begin(items_count, items_height); } // [removed in 1.79] #endif }; @@ -2850,26 +2956,32 @@ struct ImGuiListClipper #ifdef IMGUI_DEFINE_MATH_OPERATORS #define IMGUI_DEFINE_MATH_OPERATORS_IMPLEMENTED IM_MSVC_RUNTIME_CHECKS_OFF -static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); } -static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); } -static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); } -static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); } -static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } -static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); } -static inline ImVec2 operator-(const ImVec2& lhs) { return ImVec2(-lhs.x, -lhs.y); } -static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } -static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } -static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } -static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } -static inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs) { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; } -static inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; } -static inline bool operator==(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } -static inline bool operator!=(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y; } -static inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); } -static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); } -static inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); } -static inline bool operator==(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w; } -static inline bool operator!=(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z || lhs.w != rhs.w; } +// ImVec2 operators +inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); } +inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); } +inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); } +inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); } +inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } +inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); } +inline ImVec2 operator-(const ImVec2& lhs) { return ImVec2(-lhs.x, -lhs.y); } +inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } +inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } +inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } +inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } +inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs) { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; } +inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; } +inline bool operator==(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } +inline bool operator!=(const ImVec2& lhs, const ImVec2& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y; } +// ImVec4 operators +inline ImVec4 operator*(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs); } +inline ImVec4 operator/(const ImVec4& lhs, const float rhs) { return ImVec4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs); } +inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); } +inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); } +inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); } +inline ImVec4 operator/(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w); } +inline ImVec4 operator-(const ImVec4& lhs) { return ImVec4(-lhs.x, -lhs.y, -lhs.z, -lhs.w); } +inline bool operator==(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w; } +inline bool operator!=(const ImVec4& lhs, const ImVec4& rhs) { return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z || lhs.w != rhs.w; } IM_MSVC_RUNTIME_CHECKS_RESTORE #endif @@ -3103,11 +3215,11 @@ typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* c // - VtxOffset: When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset' is enabled, // this fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices. // Backends made for <1.71. will typically ignore the VtxOffset fields. -// - The ClipRect/TextureId/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for). +// - The ClipRect/TexRef/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for). struct ImDrawCmd { ImVec4 ClipRect; // 4*4 // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates - ImTextureID TextureId; // 4-8 // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. + ImTextureRef TexRef; // 16 // Reference to a font/texture atlas (where backend called ImTextureData::SetTexID()) or to a user-provided texture ID (via e.g. ImGui::Image() calls). Both will lead to a ImTextureID value. unsigned int VtxOffset; // 4 // Start offset in vertex buffer. ImGuiBackendFlags_RendererHasVtxOffset: always 0, otherwise may be >0 to support meshes larger than 64K vertices with 16-bit indices. unsigned int IdxOffset; // 4 // Start offset in index buffer. unsigned int ElemCount; // 4 // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. @@ -3119,7 +3231,8 @@ struct ImDrawCmd ImDrawCmd() { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed // Since 1.83: returns ImTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature) - inline ImTextureID GetTexID() const { return TextureId; } + // Since 1.92: removed ImDrawCmd::TextureId field, the getter function must be used! + inline ImTextureID GetTexID() const; // == (TexRef._TexData ? TexRef._TexData->TexID : TexRef._TexID }; // Vertex layout @@ -3142,7 +3255,7 @@ IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; struct ImDrawCmdHeader { ImVec4 ClipRect; - ImTextureID TextureId; + ImTextureRef TexRef; unsigned int VtxOffset; }; @@ -3228,7 +3341,7 @@ struct ImDrawList ImDrawCmdHeader _CmdHeader; // [Internal] template of active commands. Fields should match those of CmdBuffer.back(). ImDrawListSplitter _Splitter; // [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!) ImVector _ClipRectStack; // [Internal] - ImVector _TextureIdStack; // [Internal] + ImVector _TextureStack; // [Internal] ImVector _CallbacksDataBuf; // [Internal] float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content const char* _OwnerName; // Pointer to owner window's name for debugging @@ -3241,8 +3354,8 @@ struct ImDrawList IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) IMGUI_API void PushClipRectFullScreen(); IMGUI_API void PopClipRect(); - IMGUI_API void PushTextureID(ImTextureID texture_id); - IMGUI_API void PopTextureID(); + IMGUI_API void PushTexture(ImTextureRef tex_ref); + IMGUI_API void PopTexture(); inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); } inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); } @@ -3280,12 +3393,12 @@ struct ImDrawList IMGUI_API void AddConcavePolyFilled(const ImVec2* points, int num_points, ImU32 col); // Image primitives - // - Read FAQ to understand what ImTextureID is. + // - Read FAQ to understand what ImTextureID/ImTextureRef are. // - "p_min" and "p_max" represent the upper-left and lower-right corners of the rectangle. // - "uv_min" and "uv_max" represent the normalized texture coordinates to use for those corners. Using (0,0)->(1,1) texture coordinates will generally display the entire texture. - IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min = ImVec2(0, 0), const ImVec2& uv_max = ImVec2(1, 1), ImU32 col = IM_COL32_WHITE); - IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1 = ImVec2(0, 0), const ImVec2& uv2 = ImVec2(1, 0), const ImVec2& uv3 = ImVec2(1, 1), const ImVec2& uv4 = ImVec2(0, 1), ImU32 col = IM_COL32_WHITE); - IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags = 0); + IMGUI_API void AddImage(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min = ImVec2(0, 0), const ImVec2& uv_max = ImVec2(1, 1), ImU32 col = IM_COL32_WHITE); + IMGUI_API void AddImageQuad(ImTextureRef tex_ref, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1 = ImVec2(0, 0), const ImVec2& uv2 = ImVec2(1, 0), const ImVec2& uv3 = ImVec2(1, 1), const ImVec2& uv4 = ImVec2(0, 1), ImU32 col = IM_COL32_WHITE); + IMGUI_API void AddImageRounded(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags = 0); // Shadows primitives // [BETA] API @@ -3358,6 +3471,10 @@ struct ImDrawList inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } // Write vertex with unique index // Obsolete names +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline void PushTextureID(ImTextureRef tex_ref) { PushTexture(tex_ref); } // RENAMED in 1.92.x + inline void PopTextureID() { PopTexture(); } // RENAMED in 1.92.x +#endif //inline void AddEllipse(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f) { AddEllipse(center, ImVec2(radius_x, radius_y), col, rot, num_segments, thickness); } // OBSOLETED in 1.90.5 (Mar 2024) //inline void AddEllipseFilled(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0) { AddEllipseFilled(center, ImVec2(radius_x, radius_y), col, rot, num_segments); } // OBSOLETED in 1.90.5 (Mar 2024) //inline void PathEllipticalArcTo(const ImVec2& center, float radius_x, float radius_y, float rot, float a_min, float a_max, int num_segments = 0) { PathEllipticalArcTo(center, ImVec2(radius_x, radius_y), rot, a_min, a_max, num_segments); } // OBSOLETED in 1.90.5 (Mar 2024) @@ -3365,14 +3482,15 @@ struct ImDrawList //inline void PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0) { PathBezierCubicCurveTo(p2, p3, p4, num_segments); } // OBSOLETED in 1.80 (Jan 2021) // [Internal helpers] + IMGUI_API void _SetDrawListSharedData(ImDrawListSharedData* data); IMGUI_API void _ResetForNewFrame(); IMGUI_API void _ClearFreeMemory(); IMGUI_API void _PopUnusedDrawCmd(); IMGUI_API void _TryMergeDrawCmds(); IMGUI_API void _OnChangedClipRect(); - IMGUI_API void _OnChangedTextureID(); + IMGUI_API void _OnChangedTexture(); IMGUI_API void _OnChangedVtxOffset(); - IMGUI_API void _SetTextureID(ImTextureID texture_id); + IMGUI_API void _SetTexture(ImTextureRef tex_ref); IMGUI_API int _CalcCircleAutoSegmentCount(float radius) const; IMGUI_API void _PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step); IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); @@ -3384,14 +3502,15 @@ struct ImDrawList struct ImDrawData { bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. - int CmdListsCount; // Number of ImDrawList* to render + int CmdListsCount; // Number of ImDrawList* to render. (== CmdLists.Size). Exists for legacy reason. int TotalIdxCount; // For convenience, sum of all ImDrawList's IdxBuffer.Size int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size ImVector CmdLists; // Array of ImDrawList* to render. The ImDrawLists are owned by ImGuiContext and only pointed to from here. ImVec2 DisplayPos; // Top-left position of the viewport to render (== top-left of the orthogonal projection matrix to use) (== GetMainViewport()->Pos for the main viewport, == (0.0) in most single-viewport applications) ImVec2 DisplaySize; // Size of the viewport to render (== GetMainViewport()->Size for the main viewport, == io.DisplaySize in most single-viewport applications) - ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Based on io.DisplayFramebufferScale. Generally (1,1) on normal display, (2,2) on OSX with Retina display. + ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Copied from viewport->FramebufferScale (== io.DisplayFramebufferScale for main viewport). Generally (1,1) on normal display, (2,2) on OSX with Retina display. ImGuiViewport* OwnerViewport; // Viewport carrying the ImDrawData instance, might be of use to the renderer (generally not). + ImVector* Textures; // List of textures to update. Most of the times the list is shared by all ImDrawData, has only 1 texture and it doesn't need any update. This almost always points to ImGui::GetPlatformIO().Textures[]. May be overriden or set to NULL if you want to manually update textures. // Functions ImDrawData() { Clear(); } @@ -3401,6 +3520,87 @@ struct ImDrawData IMGUI_API void ScaleClipRects(const ImVec2& fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than Dear ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. }; +//----------------------------------------------------------------------------- +// [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) +//----------------------------------------------------------------------------- +// In principle, the only data types that user/application code should care about are 'ImTextureRef' and 'ImTextureID'. +// They are defined above in this header file. Read their description to the difference between ImTextureRef and ImTextureID. +// FOR ALL OTHER ImTextureXXXX TYPES: ONLY CORE LIBRARY AND RENDERER BACKENDS NEED TO KNOW AND CARE ABOUT THEM. +//----------------------------------------------------------------------------- + +#undef Status // X11 headers are leaking this. + +// We intentionally support a limited amount of texture formats to limit burden on CPU-side code and extension. +// Most standard backends only support RGBA32 but we provide a single channel option for low-resource/embedded systems. +enum ImTextureFormat +{ + ImTextureFormat_RGBA32, // 4 components per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 + ImTextureFormat_Alpha8, // 1 component per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight +}; + +// Status of a texture to communicate with Renderer Backend. +enum ImTextureStatus +{ + ImTextureStatus_OK, + ImTextureStatus_Destroyed, // Backend destroyed the texture. + ImTextureStatus_WantCreate, // Requesting backend to create the texture. Set status OK when done. + ImTextureStatus_WantUpdates, // Requesting backend to update specific blocks of pixels (write to texture portions which have never been used before). Set status OK when done. + ImTextureStatus_WantDestroy, // Requesting backend to destroy the texture. Set status to Destroyed when done. +}; + +// Coordinates of a rectangle within a texture. +// When a texture is in ImTextureStatus_WantUpdates state, we provide a list of individual rectangles to copy to the graphics system. +// You may use ImTextureData::Updates[] for the list, or ImTextureData::UpdateBox for a single bounding box. +struct ImTextureRect +{ + unsigned short x, y; // Upper-left coordinates of rectangle to update + unsigned short w, h; // Size of rectangle to update (in pixels) +}; + +// Specs and pixel storage for a texture used by Dear ImGui. +// This is only useful for (1) core library and (2) backends. End-user/applications do not need to care about this. +// Renderer Backends will create a GPU-side version of this. +// Why does we store two identifiers: TexID and BackendUserData? +// - ImTextureID TexID = lower-level identifier stored in ImDrawCmd. ImDrawCmd can refer to textures not created by the backend, and for which there's no ImTextureData. +// - void* BackendUserData = higher-level opaque storage for backend own book-keeping. Some backends may have enough with TexID and not need both. + // In columns below: who reads/writes each fields? 'r'=read, 'w'=write, 'core'=main library, 'backend'=renderer backend +struct ImTextureData +{ + //------------------------------------------ core / backend --------------------------------------- + int UniqueID; // w - // Sequential index to facilitate identifying a texture when debugging/printing. Unique per atlas. + ImTextureStatus Status; // rw rw // ImTextureStatus_OK/_WantCreate/_WantUpdates/_WantDestroy. Always use SetStatus() to modify! + void* BackendUserData; // - rw // Convenience storage for backend. Some backends may have enough with TexID. + ImTextureID TexID; // r w // Backend-specific texture identifier. Always use SetTexID() to modify! The identifier will stored in ImDrawCmd::GetTexID() and passed to backend's RenderDrawData function. + ImTextureFormat Format; // w r // ImTextureFormat_RGBA32 (default) or ImTextureFormat_Alpha8 + int Width; // w r // Texture width + int Height; // w r // Texture height + int BytesPerPixel; // w r // 4 or 1 + unsigned char* Pixels; // w r // Pointer to buffer holding 'Width*Height' pixels and 'Width*Height*BytesPerPixels' bytes. + ImTextureRect UsedRect; // w r // Bounding box encompassing all past and queued Updates[]. + ImTextureRect UpdateRect; // w r // Bounding box encompassing all queued Updates[]. + ImVector Updates; // w r // Array of individual updates. + int UnusedFrames; // w r // In order to facilitate handling Status==WantDestroy in some backend: this is a count successive frames where the texture was not used. Always >0 when Status==WantDestroy. + unsigned short RefCount; // w r // Number of contexts using this texture. Used during backend shutdown. + bool UseColors; // w r // Tell whether our texture data is known to use colors (rather than just white + alpha). + bool WantDestroyNextFrame; // rw - // [Internal] Queued to set ImTextureStatus_WantDestroy next frame. May still be used in the current frame. + + // Functions + ImTextureData() { memset(this, 0, sizeof(*this)); TexID = ImTextureID_Invalid; } + ~ImTextureData() { DestroyPixels(); } + IMGUI_API void Create(ImTextureFormat format, int w, int h); + IMGUI_API void DestroyPixels(); + void* GetPixels() { IM_ASSERT(Pixels != NULL); return Pixels; } + void* GetPixelsAt(int x, int y) { IM_ASSERT(Pixels != NULL); return Pixels + (x + y * Width) * BytesPerPixel; } + int GetSizeInBytes() const { return Width * Height * BytesPerPixel; } + int GetPitch() const { return Width * BytesPerPixel; } + ImTextureRef GetTexRef() { ImTextureRef tex_ref; tex_ref._TexData = this; tex_ref._TexID = ImTextureID_Invalid; return tex_ref; } + ImTextureID GetTexID() const { return TexID; } + + // Called by Renderer backend + void SetTexID(ImTextureID tex_id) { TexID = tex_id; } // Call after creating or destroying the texture. Never modify TexID directly! + void SetStatus(ImTextureStatus status) { Status = status; } // Call after honoring a request. Never modify Status directly! +}; + //----------------------------------------------------------------------------- // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFontGlyphRangesBuilder, ImFont) //----------------------------------------------------------------------------- @@ -3426,43 +3626,56 @@ struct ImFontAtlasShadowTexConfig // A font input/source (we may rename this to ImFontSource in the future) struct ImFontConfig { + // Data Source + char Name[40]; // // Name (strictly to ease debugging, hence limited size buffer) void* FontData; // // TTF/OTF data int FontDataSize; // // TTF/OTF data size bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself). + + // Options bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. bool PixelSnapH; // false // Align every glyph AdvanceX to pixel boundaries. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. - int FontNo; // 0 // Index of font within TTF/OTF file - int OversampleH; // 0 (2) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1 or 2 depending on size. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. - int OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. - float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). - //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED IN 1.91.9: use GlyphExtraAdvanceX) - ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input. - const ImWchar* GlyphRanges; // NULL // THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). - float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font - float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs - float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. - unsigned int FontBuilderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. - float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future. - float RasterizerDensity; // 1.0f // DPI scale for rasterization, not altering other font metrics: make it easy to swap between e.g. a 100% and a 400% fonts for a zooming display. IMPORTANT: If you increase this it is expected that you increase font scale accordingly, otherwise quality may look lowered. + bool PixelSnapV; // true // Align Scaled GlyphOffset.y to pixel boundaries. + ImS8 OversampleH; // 0 (2) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1 or 2 depending on size. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. + ImS8 OversampleV; // 0 (1) // Rasterize at higher quality for sub-pixel positioning. 0 == auto == 1. This is not really useful as we don't use sub-pixel positions on the Y axis. ImWchar EllipsisChar; // 0 // Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. + float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). + const ImWchar* GlyphRanges; // NULL // *LEGACY* THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). + const ImWchar* GlyphExcludeRanges; // NULL // Pointer to a small user-provided list of Unicode ranges (2 value per range, values are inclusive, zero-terminated list). This is very close to GlyphRanges[] but designed to exclude ranges from a font source, when merging fonts with overlapping glyphs. Use "Input Glyphs Overlap Detection Tool" to find about your overlapping ranges. + //ImVec2 GlyphExtraSpacing; // 0, 0 // (REMOVED AT IT SEEMS LARGELY OBSOLETE. PLEASE REPORT IF YOU WERE USING THIS). Extra spacing (in pixels) between glyphs when rendered: essentially add to glyph->AdvanceX. Only X axis is supported for now. + ImVec2 GlyphOffset; // 0, 0 // Offset (in pixels) all glyphs from this font input. Absolute value for default size, other sizes will scale this value. + float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font. Absolute value for default size, other sizes will scale this value. + float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs + float GlyphExtraAdvanceX; // 0 // Extra spacing (in pixels) between glyphs. Please contact us if you are using this. // FIXME-NEWATLAS: Intentionally unscaled + ImU32 FontNo; // 0 // Index of font within TTF/OTF file + unsigned int FontLoaderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. + //unsigned int FontBuilderFlags; // -- // [Renamed in 1.92] Ue FontLoaderFlags. + float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future. + float RasterizerDensity; // 1.0f // [LEGACY: this only makes sense when ImGuiBackendFlags_RendererHasTextures is not supported] DPI scale multiplier for rasterization. Not altering other font metrics: makes it easy to swap between e.g. a 100% and a 400% fonts for a zooming display, or handle Retina screen. IMPORTANT: If you change this it is expected that you increase/decrease font scale roughly to the inverse of this, otherwise quality may look lowered. // [Internal] - char Name[40]; // Name (strictly to ease debugging) - ImFont* DstFont; + ImFontFlags Flags; // Font flags (don't use just yet, will be exposed in upcoming 1.92.X updates) + ImFont* DstFont; // Target font (as we merging fonts, multiple ImFontConfig may target the same font) + const ImFontLoader* FontLoader; // Custom font backend for this source (default source is the one stored in ImFontAtlas) + void* FontLoaderData; // Font loader opaque storage (per font config) IMGUI_API ImFontConfig(); }; // Hold rendering data for one glyph. -// (Note: some language parsers may fail to convert the 31+1 bitfield members, in this case maybe drop store a single u32 or we can rework this) +// (Note: some language parsers may fail to convert the bitfield members, in this case maybe drop store a single u32 or we can rework this) struct ImFontGlyph { unsigned int Colored : 1; // Flag to indicate glyph is colored and should generally ignore tinting (make it usable with no shift on little-endian as this is used in loops) unsigned int Visible : 1; // Flag to indicate glyph has no visible pixels (e.g. space). Allow early out when rendering. - unsigned int Codepoint : 30; // 0x0000..0x10FFFF - float AdvanceX; // Horizontal distance to advance layout with - float X0, Y0, X1, Y1; // Glyph corners - float U0, V0, U1, V1; // Texture coordinates + unsigned int SourceIdx : 4; // Index of source in parent font + unsigned int Codepoint : 26; // 0x0000..0x10FFFF + float AdvanceX; // Horizontal distance to advance cursor/layout position. + float X0, Y0, X1, Y1; // Glyph corners. Offsets from current cursor/layout position. + float U0, V0, U1, V1; // Texture coordinates for the current value of ImFontAtlas->TexRef. Cached equivalent of calling GetCustomRect() with PackId. + int PackId; // [Internal] ImFontAtlasRectId value (FIXME: Cold data, could be moved elsewhere?) + + ImFontGlyph() { memset(this, 0, sizeof(*this)); PackId = -1; } }; // Helper to build glyph ranges from text/string data. Feed your application strings/characters to it then call BuildRanges(). @@ -3481,20 +3694,21 @@ struct ImFontGlyphRangesBuilder IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges }; -// See ImFontAtlas::AddCustomRectXXX functions. -struct ImFontAtlasCustomRect -{ - unsigned short X, Y; // Output // Packed position in Atlas +// An opaque identifier to a rectangle in the atlas. -1 when invalid. +// The rectangle may move and UV may be invalidated, use GetCustomRect() to retrieve it. +typedef int ImFontAtlasRectId; +#define ImFontAtlasRectId_Invalid -1 - // [Internal] - unsigned short Width, Height; // Input // Desired rectangle dimension - unsigned int GlyphID : 31; // Input // For custom font glyphs only (ID < 0x110000) - unsigned int GlyphColored : 1; // Input // For custom font glyphs only: glyph is colored, removed tinting. - float GlyphAdvanceX; // Input // For custom font glyphs only: glyph xadvance - ImVec2 GlyphOffset; // Input // For custom font glyphs only: glyph display offset - ImFont* Font; // Input // For custom font glyphs only: target font - ImFontAtlasCustomRect() { X = Y = 0xFFFF; Width = Height = 0; GlyphID = 0; GlyphColored = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; } - bool IsPacked() const { return X != 0xFFFF; } +// Output of ImFontAtlas::GetCustomRect() when using custom rectangles. +// Those values may not be cached/stored as they are only valid for the current value of atlas->TexRef +// (this is in theory derived from ImTextureRect but we use separate structures for reasons) +struct ImFontAtlasRect +{ + unsigned short x, y; // Position (in current texture) + unsigned short w, h; // Size + ImVec2 uv0, uv1; // UV coordinates (in current texture) + + ImFontAtlasRect() { memset(this, 0, sizeof(*this)); } }; // Flags for ImFontAtlas build @@ -3510,12 +3724,14 @@ enum ImFontAtlasFlags_ // - One or more fonts. // - Custom graphics data needed to render the shapes needed by Dear ImGui. // - Mouse cursor shapes for software cursor rendering (unless setting 'Flags |= ImFontAtlasFlags_NoMouseCursors' in the font atlas). -// It is the user-code responsibility to setup/build the atlas, then upload the pixel data into a texture accessible by your graphics api. -// - Optionally, call any of the AddFont*** functions. If you don't call any, the default font embedded in the code will be loaded for you. -// - Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. -// - Upload the pixels data into a texture within your graphics system (see imgui_impl_xxxx.cpp examples) +// - If you don't call any AddFont*** functions, the default font embedded in the code will be loaded for you. +// It is the rendering backend responsibility to upload texture into your graphics API: +// - ImGui_ImplXXXX_RenderDrawData() functions generally iterate platform_io->Textures[] to create/update/destroy each ImTextureData instance. +// - Backend then set ImTextureData's TexID and BackendUserData. +// - Texture id are passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID/ImTextureRef for more details. +// Legacy path: +// - Call Build() + GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. // - Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture in a format natural to your graphics API. -// This value will be passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID for more details. // Common pitfalls: // - If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the // atlas is build (when calling GetTexData*** or Build()). We only copy the pointer, not the data. @@ -3529,35 +3745,49 @@ struct ImFontAtlas IMGUI_API ~ImFontAtlas(); IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg); IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); - IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); - IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_data_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed. - IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_data_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp. - IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter. - IMGUI_API void ClearInputData(); // Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts. - IMGUI_API void ClearFonts(); // Clear input+output font data (same as ClearInputData() + glyphs storage, UV coordinates). - IMGUI_API void ClearTexData(); // Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. - IMGUI_API void Clear(); // Clear all input and output. + IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); + IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_data_size, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed. + IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_data_size, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp. + IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels = 0.0f, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter. + IMGUI_API void RemoveFont(ImFont* font); - // Build atlas, retrieve pixel data. - // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). - // The pitch is always = Width * BytesPerPixels (1 or 4) - // Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into - // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste. - IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions. - IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel - IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel - bool IsBuilt() const { return Fonts.Size > 0 && TexReady; } // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent... - void SetTexID(ImTextureID id) { TexID = id; } + IMGUI_API void Clear(); // Clear everything (input fonts, output glyphs/textures) + IMGUI_API void CompactCache(); // Compact cached glyphs and texture. + IMGUI_API void SetFontLoader(const ImFontLoader* font_loader); // Change font loader at runtime. + + // As we are transitioning toward a new font system, we expect to obsolete those soon: + IMGUI_API void ClearInputData(); // [OBSOLETE] Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts. + IMGUI_API void ClearFonts(); // [OBSOLETE] Clear input+output font data (same as ClearInputData() + glyphs storage, UV coordinates). + IMGUI_API void ClearTexData(); // [OBSOLETE] Clear CPU-side copy of the texture data. Saves RAM once the texture has been copied to graphics memory. + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + // Legacy path for build atlas + retrieving pixel data. + // - User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). + // - The pitch is always = Width * BytesPerPixels (1 or 4) + // - Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into + // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste. + // - From 1.92 with backends supporting ImGuiBackendFlags_RendererHasTextures: + // - Calling Build(), GetTexDataAsAlpha8(), GetTexDataAsRGBA32() is not needed. + // - In backend: replace calls to ImFontAtlas::SetTexID() with calls to ImTextureData::SetTexID() after honoring texture creation. + IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions. + IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel + IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel + void SetTexID(ImTextureID id) { IM_ASSERT(TexRef._TexID == ImTextureID_Invalid); TexRef._TexData->TexID = id; } // Called by legacy backends. May be called before texture creation. + void SetTexID(ImTextureRef id) { IM_ASSERT(TexRef._TexID == ImTextureID_Invalid && id._TexData == NULL); TexRef._TexData->TexID = id._TexID; } // Called by legacy backends. + bool IsBuilt() const { return Fonts.Size > 0 && TexIsBuilt; } // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent.. +#endif //------------------------------------------- // Glyph Ranges //------------------------------------------- + // Since 1.92: specifying glyph ranges is only useful/necessary if your backend doesn't support ImGuiBackendFlags_RendererHasTextures! + IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) // NB: Make sure that your string are UTF-8 and NOT in your local code page. // Read https://github.com/ocornut/imgui/blob/master/docs/FONTS.md/#about-utf-8-encoding for details. // NB: Consider using ImFontGlyphRangesBuilder to build glyph ranges from textual data. - IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin IMGUI_API const ImWchar* GetGlyphRangesGreek(); // Default + Greek and Coptic IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 2999 Ideographs @@ -3566,24 +3796,32 @@ struct ImFontAtlas IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters IMGUI_API const ImWchar* GetGlyphRangesVietnamese(); // Default + Vietnamese characters +#endif //------------------------------------------- // [ALPHA] Custom Rectangles/Glyphs API //------------------------------------------- - // You can request arbitrary rectangles to be packed into the atlas, for your own purposes. - // - After calling Build(), you can query the rectangle position and render your pixels. - // - If you render colored output, set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of preferred texture format. - // - You can also request your rectangles to be mapped as font glyph (given a font + Unicode point), - // so you can render e.g. custom colorful icons and use them as regular glyphs. + // Register and retrieve custom rectangles + // - You can request arbitrary rectangles to be packed into the atlas, for your own purpose. + // - Since 1.92.X, packing is done immediately in the function call (previously packing was done during the Build call) + // - You can render your pixels into the texture right after calling the AddCustomRect() functions. + // - VERY IMPORTANT: + // - Texture may be created/resized at any time when calling ImGui or ImFontAtlas functions. + // - IT WILL INVALIDATE RECTANGLE DATA SUCH AS UV COORDINATES. Always use latest values from GetCustomRect(). + // - UV coordinates are associated to the current texture identifier aka 'atlas->TexRef'. Both TexRef and UV coordinates are typically changed at the same time. + // - If you render colored output into your custom rectangles: set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of preferred texture format. // - Read docs/FONTS.md for more details about using colorful icons. - // - Note: this API may be redesigned later in order to support multi-monitor varying DPI settings. - IMGUI_API int AddCustomRectRegular(int width, int height); - IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); - ImFontAtlasCustomRect* GetCustomRectByIndex(int index) { IM_ASSERT(index >= 0); return &CustomRects[index]; } - - // [Internal] - IMGUI_API void CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const; + // - Note: this API may be reworked further in order to facilitate supporting e.g. multi-monitor, varying DPI settings. + // - (Pre-1.92 names) ------------> (1.92 names) + // - GetCustomRectByIndex() --> Use GetCustomRect() + // - CalcCustomRectUV() --> Use GetCustomRect() and read uv0, uv1 fields. + // - AddCustomRectRegular() --> Renamed to AddCustomRect() + // - AddCustomRectFontGlyph() --> Prefer using custom ImFontLoader inside ImFontConfig + // - ImFontAtlasCustomRect --> Renamed to ImFontAtlasRect + IMGUI_API ImFontAtlasRectId AddCustomRect(int width, int height, ImFontAtlasRect* out_r = NULL);// Register a rectangle. Return -1 (ImFontAtlasRectId_Invalid) on error. + IMGUI_API void RemoveCustomRect(ImFontAtlasRectId id); // Unregister a rectangle. Existing pixels will stay in texture until resized / garbage collected. + IMGUI_API bool GetCustomRect(ImFontAtlasRectId id, ImFontAtlasRect* out_r) const; // Get rectangle coordinates for current texture. Valid immediately, never store this (read above)! //------------------------------------------- // Members @@ -3591,101 +3829,182 @@ struct ImFontAtlas // Input ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) - ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. - int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. + ImTextureFormat TexDesiredFormat; // Desired texture format (default to ImTextureFormat_RGBA32 but may be changed to ImTextureFormat_Alpha8). int TexGlyphPadding; // FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false). + int TexMinWidth; // Minimum desired texture width. Must be a power of two. Default to 512. + int TexMinHeight; // Minimum desired texture height. Must be a power of two. Default to 128. + int TexMaxWidth; // Maximum desired texture width. Must be a power of two. Default to 8192. + int TexMaxHeight; // Maximum desired texture height. Must be a power of two. Default to 8192. void* UserData; // Store your own atlas related user-data (if e.g. you have multiple font atlas). + // Output + // - Because textures are dynamically created/resized, the current texture identifier may changed at *ANY TIME* during the frame. + // - This should not affect you as you can always use the latest value. But note that any precomputed UV coordinates are only valid for the current TexRef. +#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImTextureRef TexRef; // Latest texture identifier == TexData->GetTexRef(). +#else + union { ImTextureRef TexRef; ImTextureRef TexID; }; // Latest texture identifier == TexData->GetTexRef(). // RENAMED TexID to TexRef in 1.92.x +#endif + ImTextureData* TexData; // Latest texture. + // [Internal] - // NB: Access texture data via GetTexData*() calls! Which will setup a default font for you. - bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. - bool TexReady; // Set when texture was built matching current font input - bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format. - unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight - unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 - int TexWidth; // Texture width calculated during Build(). - int TexHeight; // Texture height calculated during Build(). - ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight) - ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel + ImVector TexList; // Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). DO NOT USE DIRECTLY, USE GetDrawData().Textures[]/GetPlatformIO().Textures[] instead! + bool Locked; // Marked as locked during ImGui::NewFrame()..EndFrame() scope if TexUpdates are not supported. Any attempt to modify the atlas will assert. + bool RendererHasTextures;// Copy of (BackendFlags & ImGuiBackendFlags_RendererHasTextures) from supporting context. + bool TexIsBuilt; // Set when texture was built matching current font input. Mostly useful for legacy IsBuilt() call. + bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format or conversion process. + ImVec2 TexUvScale; // = (1.0f/TexData->TexWidth, 1.0f/TexData->TexHeight). May change as new texture gets created. + ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel. May change as new texture gets created. ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. - ImVector CustomRects; // Rectangles for packing custom texture data into the atlas. ImVector Sources; // Source/configuration data ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines - - // [Internal] Font builder - const ImFontBuilderIO* FontBuilderIO; // Opaque interface to a font builder (default to stb_truetype, can be changed to use FreeType by defining IMGUI_ENABLE_FREETYPE). - unsigned int FontBuilderFlags; // Shared flags (for all fonts) for custom font builder. THIS IS BUILD IMPLEMENTATION DEPENDENT. Per-font override is also available in ImFontConfig. - - // [Internal] Packing data - int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors - int PackIdLines; // Custom texture rectangle ID for baked anti-aliased lines + int TexNextUniqueID; // Next value to be stored in TexData->UniqueID + int FontNextUniqueID; // Next value to be stored in ImFont->FontID + ImVector DrawListSharedDatas; // List of users for this atlas. Typically one per Dear ImGui context. + ImFontAtlasBuilder* Builder; // Opaque interface to our data that doesn't need to be public and may be discarded when rebuilding. + const ImFontLoader* FontLoader; // Font loader opaque interface (default to use FreeType when IMGUI_ENABLE_FREETYPE is defined, otherwise default to use stb_truetype). Use SetFontLoader() to change this at runtime. + const char* FontLoaderName; // Font loader name (for display e.g. in About box) == FontLoader->Name + void* FontLoaderData; // Font backend opaque storage + unsigned int FontLoaderFlags; // Shared flags (for all fonts) for font loader. THIS IS BUILD IMPLEMENTATION DEPENDENT (e.g. Per-font override is also available in ImFontConfig). + int RefCount; // Number of contexts using this atlas + ImGuiContext* OwnerContext; // Context which own the atlas will be in charge of updating and destroying it. // [Internal] Shadow data - int ShadowRectIds[2]; // IDs of rect for shadow textures + ImFontAtlasRectId ShadowRectIds[2]; // IDs of rect for shadow textures ImVec4 ShadowRectUvs[10]; // UV coordinates for shadow textures, 9 for the rectangle shadows and the final entry for the convex shape shadows ImFontAtlasShadowTexConfig ShadowTexConfig; // Shadow texture baking config // [Obsolete] - //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ - //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + // Legacy: You can request your rectangles to be mapped as font glyph (given a font + Unicode point), so you can render e.g. custom colorful icons and use them as regular glyphs. --> Prefer using a custom ImFontLoader. + ImFontAtlasRect TempRect; // For old GetCustomRectByIndex() API + inline ImFontAtlasRectId AddCustomRectRegular(int w, int h) { return AddCustomRect(w, h); } // RENAMED in 1.92.X + inline const ImFontAtlasRect* GetCustomRectByIndex(ImFontAtlasRectId id) { return GetCustomRect(id, &TempRect) ? &TempRect : NULL; } // OBSOLETED in 1.92.X + inline void CalcCustomRectUV(const ImFontAtlasRect* r, ImVec2* out_uv_min, ImVec2* out_uv_max) const { *out_uv_min = r->uv0; *out_uv_max = r->uv1; } // OBSOLETED in 1.92.X + IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // OBSOLETED in 1.92.X: Use custom ImFontLoader in ImFontConfig + IMGUI_API ImFontAtlasRectId AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int w, int h, float advance_x, const ImVec2& offset = ImVec2(0, 0)); // ADDED AND OBSOLETED in 1.92.X +#endif + //unsigned int FontBuilderFlags; // OBSOLETED in 1.92.X: Renamed to FontLoaderFlags. + //int TexDesiredWidth; // OBSOLETED in 1.92.X: Force texture width before calling Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height) + //typedef ImFontAtlasRect ImFontAtlasCustomRect; // OBSOLETED in 1.92.X + //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ + //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ }; -// Font runtime data and rendering -// ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). -struct ImFont +// Font runtime data for a given size +// Important: pointers to ImFontBaked are only valid for the current frame. +struct ImFontBaked { // [Internal] Members: Hot ~20/24 bytes (for CalcTextSize) ImVector IndexAdvanceX; // 12-16 // out // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this info, and are often bottleneck in large UI). - float FallbackAdvanceX; // 4 // out // = FallbackGlyph->AdvanceX - float FontSize; // 4 // in // Height of characters/line, set during loading (don't change after loading) + float FallbackAdvanceX; // 4 // out // FindGlyph(FallbackChar)->AdvanceX + float Size; // 4 // in // Height of characters/line, set during loading (doesn't change after loading) + float RasterizerDensity; // 4 // in // Density this is baked at - // [Internal] Members: Hot ~28/40 bytes (for RenderText loop) + // [Internal] Members: Hot ~28/36 bytes (for RenderText loop) ImVector IndexLookup; // 12-16 // out // Sparse. Index glyphs by Unicode code-point. ImVector Glyphs; // 12-16 // out // All glyphs. - ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar) + int FallbackGlyphIndex; // 4 // out // Index of FontFallbackChar - // [Internal] Members: Cold ~32/40 bytes + // [Internal] Members: Cold + float Ascent, Descent; // 4+4 // out // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) + unsigned int MetricsTotalSurface:26;// 3 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) + unsigned int WantDestroy:1; // 0 // // Queued for destroy + unsigned int LockLoadingFallback:1; // 0 // // + int LastUsedFrame; // 4 // // Record of that time this was bounds + ImGuiID BakedId; // 4 // + ImFont* ContainerFont; // 4-8 // in // Parent font + void* FontLoaderDatas; // 4-8 // // Font loader opaque storage (per baked font * sources): single contiguous buffer allocated by imgui, passed to loader. + + // Functions + IMGUI_API ImFontBaked(); + IMGUI_API void ClearOutputData(); + IMGUI_API ImFontGlyph* FindGlyph(ImWchar c); // Return U+FFFD glyph if requested glyph doesn't exists. + IMGUI_API ImFontGlyph* FindGlyphNoFallback(ImWchar c); // Return NULL if glyph doesn't exist + IMGUI_API float GetCharAdvance(ImWchar c); + IMGUI_API bool IsGlyphLoaded(ImWchar c); +}; + +// Font flags +// (in future versions as we redesign font loading API, this will become more important and better documented. for now please consider this as internal/advanced use) +enum ImFontFlags_ +{ + ImFontFlags_None = 0, + ImFontFlags_NoLoadError = 1 << 1, // Disable throwing an error/assert when calling AddFontXXX() with missing file/data. Calling code is expected to check AddFontXXX() return value. + ImFontFlags_NoLoadGlyphs = 1 << 2, // [Internal] Disable loading new glyphs. + ImFontFlags_LockBakedSizes = 1 << 3, // [Internal] Disable loading new baked sizes, disable garbage collecting current ones. e.g. if you want to lock a font to a single size. Important: if you use this to preload given sizes, consider the possibility of multiple font density used on Retina display. +}; + +// Font runtime data and rendering +// - ImFontAtlas automatically loads a default embedded font for you if you didn't load one manually. +// - Since 1.92.X a font may be rendered as any size! Therefore a font doesn't have one specific size. +// - Use 'font->GetFontBaked(size)' to retrieve the ImFontBaked* corresponding to a given size. +// - If you used g.Font + g.FontSize (which is frequent from the ImGui layer), you can use g.FontBaked as a shortcut, as g.FontBaked == g.Font->GetFontBaked(g.FontSize). +struct ImFont +{ + // [Internal] Members: Hot ~12-20 bytes + ImFontBaked* LastBaked; // 4-8 // Cache last bound baked. NEVER USE DIRECTLY. Use GetFontBaked(). + ImFontAtlas* ContainerAtlas; // 4-8 // What we have been loaded into. + ImFontFlags Flags; // 4 // Font flags. + float CurrentRasterizerDensity; // Current rasterizer density. This is a varying state of the font. + + // [Internal] Members: Cold ~24-52 bytes // Conceptually Sources[] is the list of font sources merged to create this font. - ImFontAtlas* ContainerAtlas; // 4-8 // out // What we has been loaded into - ImFontConfig* Sources; // 4-8 // in // Pointer within ContainerAtlas->Sources[], to SourcesCount instances - short SourcesCount; // 2 // in // Number of ImFontConfig involved in creating this font. Usually 1, or >1 when merging multiple font sources into one ImFont. - short EllipsisCharCount; // 1 // out // 1 or 3 + ImGuiID FontId; // Unique identifier for the font + float LegacySize; // 4 // in // Font size passed to AddFont(). Use for old code calling PushFont() expecting to use that size. (use ImGui::GetFontBaked() to get font baked at current bound size). + ImVector Sources; // 16 // in // List of sources. Pointers within ContainerAtlas->Sources[] ImWchar EllipsisChar; // 2-4 // out // Character used for ellipsis rendering ('...'). ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') - float EllipsisWidth; // 4 // out // Total ellipsis Width - float EllipsisCharStep; // 4 // out // Step between characters when EllipsisCount > 0 - float Scale; // 4 // in // Base font scale (1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() - float Ascent, Descent; // 4+4 // out // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) - int MetricsTotalSurface;// 4 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) - bool DirtyLookupTables; // 1 // out // ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 16 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. + bool EllipsisAutoBake; // 1 // // Mark when the "..." glyph needs to be generated. + ImGuiStorage RemapPairs; // 16 // // Remapping pairs when using AddRemapChar(), otherwise empty. +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + float Scale; // 4 // in // Legacy base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() +#endif // Methods IMGUI_API ImFont(); IMGUI_API ~ImFont(); - IMGUI_API ImFontGlyph* FindGlyph(ImWchar c); - IMGUI_API ImFontGlyph* FindGlyphNoFallback(ImWchar c); - float GetCharAdvance(ImWchar c) { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; } + IMGUI_API bool IsGlyphInFont(ImWchar c); bool IsLoaded() const { return ContainerAtlas != NULL; } - const char* GetDebugName() const { return Sources ? Sources->Name : ""; } + const char* GetDebugName() const { return Sources.Size ? Sources[0]->Name : ""; } // Fill ImFontConfig::Name. // [Internal] Don't use! // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. + IMGUI_API ImFontBaked* GetFontBaked(float font_size, float density = -1.0f); // Get or create baked data for given size IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL); // utf8 - IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width); - IMGUI_API void RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c); + IMGUI_API const char* CalcWordWrapPosition(float size, const char* text, const char* text_end, float wrap_width); + IMGUI_API void RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c, const ImVec4* cpu_fine_clip = NULL); IMGUI_API void RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false); +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) { return CalcWordWrapPosition(LegacySize * scale, text, text_end, wrap_width); } +#endif // [Internal] Don't use! - IMGUI_API void BuildLookupTable(); IMGUI_API void ClearOutputData(); - IMGUI_API void GrowIndex(int new_size); - IMGUI_API void AddGlyph(const ImFontConfig* src_cfg, ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x); - IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. + IMGUI_API void AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint); // Makes 'from_codepoint' character points to 'to_codepoint' glyph. IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); }; +// This is provided for consistency (but we don't actually use this) +inline ImTextureID ImTextureRef::GetTexID() const +{ + IM_ASSERT(!(_TexData != NULL && _TexID != ImTextureID_Invalid)); + return _TexData ? _TexData->TexID : _TexID; +} + +// Using an indirection to avoid patching ImDrawCmd after a SetTexID() call (but this could be an alternative solution too) +inline ImTextureID ImDrawCmd::GetTexID() const +{ + // If you are getting this assert: A renderer backend with support for ImGuiBackendFlags_RendererHasTextures (1.92) + // must iterate and handle ImTextureData requests stored in ImDrawData::Textures[]. + ImTextureID tex_id = TexRef._TexData ? TexRef._TexData->TexID : TexRef._TexID; // == TexRef.GetTexID() above. + if (TexRef._TexData != NULL) + IM_ASSERT(tex_id != ImTextureID_Invalid && "ImDrawCmd is referring to ImTextureData that wasn't uploaded to graphics system. Backend must call ImTextureData::SetTexID() after handling ImTextureStatus_WantCreate request!"); + return tex_id; +} + //----------------------------------------------------------------------------- // [SECTION] Viewports //----------------------------------------------------------------------------- @@ -3725,6 +4044,7 @@ struct ImGuiViewport ImGuiViewportFlags Flags; // See ImGuiViewportFlags_ ImVec2 Pos; // Main Area: Position of the viewport (Dear ImGui coordinates are the same as OS desktop/native coordinates) ImVec2 Size; // Main Area: Size of the viewport. + ImVec2 FramebufferScale; // Density of the viewport for Retina display (always 1,1 on Windows, may be 2,2 etc on macOS/iOS). This will affect font rasterizer density. ImVec2 WorkPos; // Work Area: Position of the viewport minus task bars, menus bars, status bars (>= Pos) ImVec2 WorkSize; // Work Area: Size of the viewport minus task bars, menu bars, status bars (<= Size) float DpiScale; // 1.0f = 96 DPI = No extra scale. @@ -3837,6 +4157,10 @@ struct ImGuiPlatformIO // Input - Interface with Renderer Backend //------------------------------------------------------------------ + // Optional: Maximum texture size supported by renderer (used to adjust how we size textures). 0 if not known. + int Renderer_TextureMaxWidth; + int Renderer_TextureMaxHeight; + // Written by some backends during ImGui_ImplXXXX_RenderDrawData() call to point backend_specific ImGui_ImplXXXX_RenderState* structure. void* Renderer_RenderState; @@ -3864,6 +4188,7 @@ struct ImGuiPlatformIO ImVec2 (*Platform_GetWindowPos)(ImGuiViewport* vp); // N . . . . // void (*Platform_SetWindowSize)(ImGuiViewport* vp, ImVec2 size); // . . U . . // Set platform window client area size (ignoring OS decorations such as OS title bar etc.) ImVec2 (*Platform_GetWindowSize)(ImGuiViewport* vp); // N . . . . // Get platform window client area size + ImVec2 (*Platform_GetWindowFramebufferScale)(ImGuiViewport* vp); // N . . . . // Return viewport density. Always 1,1 on Windows, often 2,2 on Retina display on macOS/iOS. MUST BE INTEGER VALUES. void (*Platform_SetWindowFocus)(ImGuiViewport* vp); // N . . . . // Move window to front and set input focus bool (*Platform_GetWindowFocus)(ImGuiViewport* vp); // . . U . . // bool (*Platform_GetWindowMinimized)(ImGuiViewport* vp); // N . . . . // Get platform window minimized state. When minimized, we generally won't attempt to get/set size and contents will be culled more easily @@ -3890,9 +4215,13 @@ struct ImGuiPlatformIO ImVector Monitors; //------------------------------------------------------------------ - // Output - List of viewports to render into platform windows + // Output //------------------------------------------------------------------ + // Textures list (the list is updated by calling ImGui::EndFrame or ImGui::Render) + // The ImGui_ImplXXXX_RenderDrawData() function of each backend generally access this via ImDrawData::Textures which points to this. The array is available here mostly because backends will want to destroy textures on shutdown. + ImVector Textures; // List of textures used by Dear ImGui (most often 1) + contents of external texture list is automatically appended into this. + // Viewports list (the list is updated by calling ImGui::EndFrame or ImGui::Render) // (in the future we will attempt to organize this feature to remove the need for a "main viewport") ImVector Viewports; // Main viewports, followed by all secondary viewports. @@ -3909,12 +4238,14 @@ struct ImGuiPlatformMonitor ImGuiPlatformMonitor() { MainPos = MainSize = WorkPos = WorkSize = ImVec2(0, 0); DpiScale = 1.0f; PlatformHandle = NULL; } }; -// (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. +// (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. Handler is called during EndFrame(). struct ImGuiPlatformImeData { - bool WantVisible; // A widget wants the IME to be visible - ImVec2 InputPos; // Position of the input cursor - float InputLineHeight; // Line height + bool WantVisible; // A widget wants the IME to be visible. + bool WantTextInput; // A widget wants text input, not necessarily IME to be visible. This is automatically set to the upcoming value of io.WantTextInput. + ImVec2 InputPos; // Position of input cursor (for IME). + float InputLineHeight; // Line height (for IME). + ImGuiID ViewportId; // ID of platform window/viewport. ImGuiPlatformImeData() { memset(this, 0, sizeof(*this)); } }; @@ -3928,8 +4259,11 @@ struct ImGuiPlatformImeData #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { + // OBSOLETED in 1.92.0 (from June 2025) + static inline void PushFont(ImFont* font) { PushFont(font, font ? font->LegacySize : 0.0f); } + IMGUI_API void SetWindowFontScale(float scale); // Set font scale factor for current window. Prefer using PushFont(NULL, style.FontSizeBase * factor) or use style.FontScaleMain to scale all windows. // OBSOLETED in 1.91.9 (from February 2025) - IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- border_col was removed in favor of ImGuiCol_ImageBorder. + IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- 'border_col' was removed in favor of ImGuiCol_ImageBorder. If you use 'tint_col', use ImageWithBg() instead. // OBSOLETED in 1.91.0 (from July 2024) static inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } static inline void PopButtonRepeat() { PopItemFlag(); } @@ -3948,11 +4282,11 @@ namespace ImGui IMGUI_API bool ListBox(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int height_in_items = -1); // OBSOLETED in 1.89.7 (from June 2023) IMGUI_API void SetItemAllowOverlap(); // Use SetNextItemAllowOverlap() before item. - // OBSOLETED in 1.89.4 (from March 2023) - static inline void PushAllowKeyboardFocus(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } - static inline void PopAllowKeyboardFocus() { PopItemFlag(); } // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE) + //-- OBSOLETED in 1.89.4 (from March 2023) + //static inline void PushAllowKeyboardFocus(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } + //static inline void PopAllowKeyboardFocus() { PopItemFlag(); } //-- OBSOLETED in 1.89 (from August 2022) //IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); // --> Use new ImageButton() signature (explicit item id, regular FramePadding). Refer to code in 1.91 if you want to grab a copy of this version. //-- OBSOLETED in 1.88 (from May 2022) @@ -4015,6 +4349,25 @@ namespace ImGui //static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETED in 1.42 } +//-- OBSOLETED in 1.92.x: ImFontAtlasCustomRect becomes ImTextureRect +// - ImFontAtlasCustomRect::X,Y --> ImTextureRect::x,y +// - ImFontAtlasCustomRect::Width,Height --> ImTextureRect::w,h +// - ImFontAtlasCustomRect::GlyphColored --> if you need to write to this, instead you can write to 'font->Glyphs.back()->Colored' after calling AddCustomRectFontGlyph() +// We could make ImTextureRect an union to use old names, but 1) this would be confusing 2) the fix is easy 3) ImFontAtlasCustomRect was always a rather esoteric api. +typedef ImFontAtlasRect ImFontAtlasCustomRect; +/*struct ImFontAtlasCustomRect +{ + unsigned short X, Y; // Output // Packed position in Atlas + unsigned short Width, Height; // Input // [Internal] Desired rectangle dimension + unsigned int GlyphID:31; // Input // [Internal] For custom font glyphs only (ID < 0x110000) + unsigned int GlyphColored:1; // Input // [Internal] For custom font glyphs only: glyph is colored, removed tinting. + float GlyphAdvanceX; // Input // [Internal] For custom font glyphs only: glyph xadvance + ImVec2 GlyphOffset; // Input // [Internal] For custom font glyphs only: glyph display offset + ImFont* Font; // Input // [Internal] For custom font glyphs only: target font + ImFontAtlasCustomRect() { X = Y = 0xFFFF; Width = Height = 0; GlyphID = 0; GlyphColored = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; } + bool IsPacked() const { return X != 0xFFFF; } +};*/ + //-- OBSOLETED in 1.82 (from Mars 2021): flags for AddRect(), AddRectFilled(), AddImageRounded(), PathRect() //typedef ImDrawFlags ImDrawCornerFlags; //enum ImDrawCornerFlags_ diff --git a/lib/third_party/imgui/imgui/include/imgui_internal.h b/lib/third_party/imgui/imgui/include/imgui_internal.h index 20fa1074e..8d33dca0a 100644 --- a/lib/third_party/imgui/imgui/include/imgui_internal.h +++ b/lib/third_party/imgui/imgui/include/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9b +// dear imgui, v1.92.1 // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. @@ -37,6 +37,7 @@ Index of this file: // [SECTION] Tab bar, Tab item support // [SECTION] Table support // [SECTION] ImGui internal API +// [SECTION] ImFontLoader // [SECTION] ImFontAtlas internal API // [SECTION] Test Engine specific hooks (imgui_test_engine) @@ -132,7 +133,7 @@ Index of this file: //----------------------------------------------------------------------------- // Utilities -// (other types which are not forwarded declared are: ImBitArray<>, ImSpan<>, ImSpanAllocator<>, ImPool<>, ImChunkStream<>) +// (other types which are not forwarded declared are: ImBitArray<>, ImSpan<>, ImSpanAllocator<>, ImStableVector<>, ImPool<>, ImChunkStream<>) struct ImBitVector; // Store 1-bit per value struct ImRect; // An axis-aligned rectangle (2 points) struct ImGuiTextIndex; // Maintain a line index for a text buffer. @@ -140,6 +141,9 @@ struct ImGuiTextIndex; // Maintain a line index for a text buffer. // ImDrawList/ImFontAtlas struct ImDrawDataBuilder; // Helper to build a ImDrawData instance struct ImDrawListSharedData; // Data shared between all ImDrawList instances +struct ImFontAtlasBuilder; // Internal storage for incrementally packing and building a ImFontAtlas +struct ImFontAtlasPostProcessData; // Data available to potential texture post-processing functions +struct ImFontAtlasRectEntry; // Packed rectangle lookup entry // ImGui struct ImGuiBoxSelectState; // Box-selection state (currently used by multi-selection, could potentially be used by others) @@ -213,6 +217,10 @@ typedef int ImGuiTooltipFlags; // -> enum ImGuiTooltipFlags_ // F typedef int ImGuiTypingSelectFlags; // -> enum ImGuiTypingSelectFlags_ // Flags: for GetTypingSelectRequest() typedef int ImGuiWindowRefreshFlags; // -> enum ImGuiWindowRefreshFlags_ // Flags: for SetNextWindowRefreshPolicy() +// Table column indexing +typedef ImS16 ImGuiTableColumnIdx; +typedef ImU16 ImGuiTableDrawChannelIdx; + //----------------------------------------------------------------------------- // [SECTION] Context pointer // See implementation of this variable in imgui.cpp for comments and details. @@ -248,7 +256,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #define IMGUI_DEBUG_LOG_SELECTION(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_CLIPPER(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventClipper) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_IO(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) -#define IMGUI_DEBUG_LOG_FONT(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventFont) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) +#define IMGUI_DEBUG_LOG_FONT(...) do { ImGuiContext* g2 = GImGui; if (g2 && g2->DebugLogFlags & ImGuiDebugLogFlags_EventFont) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) // Called from ImFontAtlas function which may operate without a context. #define IMGUI_DEBUG_LOG_INPUTROUTING(...) do{if (g.DebugLogFlags & ImGuiDebugLogFlags_EventInputRouting)IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_DOCKING(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventDocking) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_VIEWPORT(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventViewport) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) @@ -360,6 +368,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer // - Helper: ImBitArray // - Helper: ImBitVector // - Helper: ImSpan<>, ImSpanAllocator<> +// - Helper: ImStableVector<> // - Helper: ImPool<> // - Helper: ImChunkStream<> // - Helper: ImGuiTextIndex @@ -391,6 +400,7 @@ IMGUI_API int ImStricmp(const char* str1, const char* str2); IMGUI_API int ImStrnicmp(const char* str1, const char* str2, size_t count); // Case insensitive compare to a certain count. IMGUI_API void ImStrncpy(char* dst, const char* src, size_t count); // Copy to a certain count and always zero terminate (strncpy doesn't). IMGUI_API char* ImStrdup(const char* str); // Duplicate a string. +IMGUI_API void* ImMemdup(const void* src, size_t size); // Duplicate a chunk of memory. IMGUI_API char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* str); // Copy in provided buffer, recreate buffer if needed. IMGUI_API const char* ImStrchrRange(const char* str_begin, const char* str_end, char c); // Find first occurrence of 'c' in string range. IMGUI_API const char* ImStreolRange(const char* str, const char* str_end); // End end-of-line @@ -505,6 +515,8 @@ static inline float ImTrunc(float f) static inline ImVec2 ImTrunc(const ImVec2& v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); } static inline float ImFloor(float f) { return (float)((f >= 0 || (float)(int)f == f) ? (int)f : (int)f - 1); } // Decent replacement for floorf() static inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2(ImFloor(v.x), ImFloor(v.y)); } +static inline float ImTrunc64(float f) { return (float)(ImS64)(f); } +static inline float ImRound64(float f) { return (float)(ImS64)(f + 0.5f); } static inline int ImModPositive(int a, int b) { return (a + b) % b; } static inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } static inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); } @@ -537,6 +549,14 @@ struct ImVec1 constexpr ImVec1(float _x) : x(_x) { } }; +// Helper: ImVec2i (2D vector, integer) +struct ImVec2i +{ + int x, y; + constexpr ImVec2i() : x(0), y(0) {} + constexpr ImVec2i(int _x, int _y) : x(_x), y(_y) {} +}; + // Helper: ImVec2ih (2D vector, half-size integer, for long-term packed storage) struct ImVec2ih { @@ -688,6 +708,39 @@ struct ImSpanAllocator inline void GetSpan(int n, ImSpan* span) { span->set((T*)GetSpanPtrBegin(n), (T*)GetSpanPtrEnd(n)); } }; +// Helper: ImStableVector<> +// Allocating chunks of BLOCK_SIZE items. Objects pointers are never invalidated when growing, only by clear(). +// Important: does not destruct anything! +// Implemented only the minimum set of functions we need for it. +template +struct ImStableVector +{ + int Size = 0; + int Capacity = 0; + ImVector Blocks; + + // Functions + inline ~ImStableVector() { for (T* block : Blocks) IM_FREE(block); } + + inline void clear() { Size = Capacity = 0; Blocks.clear_delete(); } + inline void resize(int new_size) { if (new_size > Capacity) reserve(new_size); Size = new_size; } + inline void reserve(int new_cap) + { + new_cap = IM_MEMALIGN(new_cap, BLOCK_SIZE); + int old_count = Capacity / BLOCK_SIZE; + int new_count = new_cap / BLOCK_SIZE; + if (new_count <= old_count) + return; + Blocks.resize(new_count); + for (int n = old_count; n < new_count; n++) + Blocks[n] = (T*)IM_ALLOC(sizeof(T) * BLOCK_SIZE); + Capacity = new_cap; + } + inline T& operator[](int i) { IM_ASSERT(i >= 0 && i < Size); return Blocks[i / BLOCK_SIZE][i % BLOCK_SIZE]; } + inline const T& operator[](int i) const { IM_ASSERT(i >= 0 && i < Size); return Blocks[i / BLOCK_SIZE][i % BLOCK_SIZE]; } + inline T* push_back(const T& v) { int i = Size; IM_ASSERT(i >= 0); if (Size == Capacity) reserve(Capacity + BLOCK_SIZE); void* ptr = &Blocks[i / BLOCK_SIZE][i % BLOCK_SIZE]; memcpy(ptr, &v, sizeof(v)); Size++; return (T*)ptr; } +}; + // Helper: ImPool<> // Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer, // Honor constructor/destructor. Add/remove invalidate all pointers. Indexes have the same lifetime as the associated object. @@ -796,17 +849,20 @@ IMGUI_API ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStorag // You may want to create your own instance of you try to ImDrawList completely without ImGui. In that case, watch out for future changes to this structure. struct IMGUI_API ImDrawListSharedData { - ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas - const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas - ImFont* Font; // Current/default font (optional, for simplified AddText overload) - float FontSize; // Current/default font size (optional, for simplified AddText overload) - float FontScale; // Current/default font scale (== FontSize / Font->FontSize) + ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) + const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->TexUvLines) + ImFontAtlas* FontAtlas; // Current font atlas + ImFont* Font; // Current font (used for simplified AddText overload) + float FontSize; // Current font size (used for for simplified AddText overload) + float FontScale; // Current font scale (== FontSize / Font->FontSize) float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() float CircleSegmentMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc float InitialFringeScale; // Initial scale to apply to AA fringe ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen() ImVector TempBuffer; // Temporary write buffer + ImVector DrawLists; // All draw lists associated to this ImDrawListSharedData + ImGuiContext* Context; // [OPTIONAL] Link to Dear ImGui context. 99% of ImDrawList/ImFontAtlas can function without an ImGui context, but this facilitate handling one legacy edge case. // Lookup tables ImVec2 ArcFastVtx[IM_DRAWLIST_ARCFAST_TABLE_SIZE]; // Sample points on the quarter of the circle. @@ -817,6 +873,7 @@ struct IMGUI_API ImDrawListSharedData const ImVec4* ShadowRectUvs; // UV coordinates for shadow texture (10 entries) ImDrawListSharedData(); + ~ImDrawListSharedData(); void SetCircleTessellationMaxError(float max_error); }; @@ -828,6 +885,13 @@ struct ImDrawDataBuilder ImDrawDataBuilder() { memset(this, 0, sizeof(*this)); } }; +struct ImFontStackData +{ + ImFont* Font; + float FontSizeBeforeScaling; // ~~ style.FontSizeBase + float FontSizeAfterScaling; // ~~ g.FontSize +}; + //----------------------------------------------------------------------------- // [SECTION] Style support //----------------------------------------------------------------------------- @@ -899,6 +963,7 @@ enum ImGuiItemFlagsPrivate_ ImGuiItemFlags_AllowOverlap = 1 << 14, // false // Allow being overlapped by another widget. Not-hovered to Hovered transition deferred by a frame. ImGuiItemFlags_NoNavDisableMouseHover = 1 << 15, // false // Nav keyboard/gamepad mode doesn't disable hover highlight (behave as if NavHighlightItemUnderNav==false). ImGuiItemFlags_NoMarkEdited = 1 << 16, // false // Skip calling MarkItemEdited() + ImGuiItemFlags_NoFocus = 1 << 17, // false // [EXPERIMENTAL: Not very well specced] Clicking doesn't take focus. Automatically sets ImGuiButtonFlags_NoFocus + ImGuiButtonFlags_NoNavFocus in ButtonBehavior(). // Controlled by widget code ImGuiItemFlags_Inputable = 1 << 20, // false // [WIP] Auto-activate input mode when tab focused. Currently only used and supported by a few items before it becomes a generic feature. @@ -927,6 +992,7 @@ enum ImGuiItemStatusFlags_ ImGuiItemStatusFlags_Visible = 1 << 8, // [WIP] Set when item is overlapping the current clipping rectangle (Used internally. Please don't use yet: API/system will change as we refactor Itemadd()). ImGuiItemStatusFlags_HasClipRect = 1 << 9, // g.LastItemData.ClipRect is valid. ImGuiItemStatusFlags_HasShortcut = 1 << 10, // g.LastItemData.Shortcut valid. Set by SetNextItemShortcut() -> ItemAdd(). + //ImGuiItemStatusFlags_FocusedByTabbing = 1 << 8, // Removed IN 1.90.1 (Dec 2023). The trigger is part of g.NavActivateId. See commit 54c1bdeceb. // Additional status + semantic for ImGuiTestEngine #ifdef IMGUI_ENABLE_TEST_ENGINE @@ -976,8 +1042,10 @@ enum ImGuiButtonFlagsPrivate_ ImGuiButtonFlags_NoHoveredOnFocus = 1 << 19, // don't report as hovered when nav focus is on this item ImGuiButtonFlags_NoSetKeyOwner = 1 << 20, // don't set key/input owner on the initial click (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!) ImGuiButtonFlags_NoTestKeyOwner = 1 << 21, // don't test key/input owner when polling the key (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!) + ImGuiButtonFlags_NoFocus = 1 << 22, // [EXPERIMENTAL: Not very well specced]. Don't focus parent window when clicking. ImGuiButtonFlags_PressedOnMask_ = ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_PressedOnDragDropHold, ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease, + //ImGuiButtonFlags_NoKeyModifiers = ImGuiButtonFlags_NoKeyModsAllowed, // Renamed in 1.91.4 }; // Extend ImGuiComboFlags_ @@ -1010,9 +1078,11 @@ enum ImGuiSelectableFlagsPrivate_ // Extend ImGuiTreeNodeFlags_ enum ImGuiTreeNodeFlagsPrivate_ { + ImGuiTreeNodeFlags_NoNavFocus = 1 << 27,// Don't claim nav focus when interacting with this item (#8551) ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 28,// FIXME-WIP: Hard-coded for CollapsingHeader() ImGuiTreeNodeFlags_UpsideDownArrow = 1 << 29,// FIXME-WIP: Turn Down arrow into an Up arrow, for reversed trees (#6517) ImGuiTreeNodeFlags_OpenOnMask_ = ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_OpenOnArrow, + ImGuiTreeNodeFlags_DrawLinesMask_ = ImGuiTreeNodeFlags_DrawLinesNone | ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes, }; enum ImGuiSeparatorFlags_ @@ -1307,15 +1377,18 @@ struct ImGuiLastItemData }; // Store data emitted by TreeNode() for usage by TreePop() -// - To implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere: store the minimum amount of data +// - To implement ImGuiTreeNodeFlags_NavLeftJumpsToParent: store the minimum amount of data // which we can't infer in TreePop(), to perform the equivalent of NavApplyItemToResult(). // Only stored when the node is a potential candidate for landing on a Left arrow jump. struct ImGuiTreeNodeStackData { ImGuiID ID; ImGuiTreeNodeFlags TreeFlags; - ImGuiItemFlags ItemFlags; // Used for nav landing - ImRect NavRect; // Used for nav landing + ImGuiItemFlags ItemFlags; // Used for nav landing + ImRect NavRect; // Used for nav landing + float DrawLinesX1; + float DrawLinesToNodesY2; + ImGuiTableColumnIdx DrawLinesTableColumn; }; // sizeof() = 20 @@ -1634,6 +1707,7 @@ enum ImGuiNavRenderCursorFlags_ ImGuiNavHighlightFlags_Compact = ImGuiNavRenderCursorFlags_Compact, // Renamed in 1.91.4 ImGuiNavHighlightFlags_AlwaysDraw = ImGuiNavRenderCursorFlags_AlwaysDraw, // Renamed in 1.91.4 ImGuiNavHighlightFlags_NoRounding = ImGuiNavRenderCursorFlags_NoRounding, // Renamed in 1.91.4 + //ImGuiNavHighlightFlags_TypeThin = ImGuiNavRenderCursorFlags_Compact, // Renamed in 1.90.2 #endif }; @@ -2204,11 +2278,13 @@ struct ImGuiMetricsConfig bool ShowDrawCmdMesh = true; bool ShowDrawCmdBoundingBoxes = true; bool ShowTextEncodingViewer = false; + bool ShowTextureUsedRect = false; bool ShowDockingNodes = false; int ShowWindowsRectsType = -1; int ShowTablesRectsType = -1; int HighlightMonitorIdx = -1; ImGuiID HighlightViewportID = 0; + bool ShowFontPreview = true; }; struct ImGuiStackLevelInfo @@ -2261,16 +2337,18 @@ struct ImGuiContextHook struct ImGuiContext { bool Initialized; - bool FontAtlasOwnedByContext; // IO.Fonts-> is owned by the ImGuiContext and will be destructed along with it. ImGuiIO IO; ImGuiPlatformIO PlatformIO; ImGuiStyle Style; ImGuiConfigFlags ConfigFlagsCurrFrame; // = g.IO.ConfigFlags at the time of NewFrame() ImGuiConfigFlags ConfigFlagsLastFrame; - ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() - float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window. - float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Base text height. - float FontScale; // == FontSize / Font->FontSize + ImVector FontAtlases; // List of font atlases used by the context (generally only contains g.IO.Fonts aka the main font atlas) + ImFont* Font; // Currently bound font. (== FontStack.back().Font) + ImFontBaked* FontBaked; // Currently bound font at currently bound size. (== Font->GetFontBaked(FontSize)) + float FontSize; // Currently bound font size == line height (== FontSizeBase + externals scales applied in the UpdateCurrentFontSize() function). + float FontSizeBase; // Font size before scaling == style.FontSizeBase == value passed to PushFont() when specified. + float FontBakedScale; // == FontBaked->Size / FontSize. Scale factor over baked size. Rarely used nowadays, very often == 1.0f. + float FontRasterizerDensity; // Current font density. Used by all calls to GetFontBaked(). float CurrentDpiScale; // Current window/viewport DpiScale == CurrentViewport->DpiScale ImDrawListSharedData DrawListSharedData; double Time; @@ -2315,7 +2393,7 @@ struct ImGuiContext ImVec2 WheelingAxisAvg; // Item/widgets state and tracking information - ImGuiID DebugDrawIdConflicts; // Set when we detect multiple items with the same identifier + ImGuiID DebugDrawIdConflictsId; // Set when we detect multiple items with the same identifier ImGuiID DebugHookIdInfo; // Will call core hooks: DebugHookIdInfo() from GetID functions, used by ID Stack Tool [next HoveredId/ActiveId to not pull in an extra cache-line] ImGuiID HoveredId; // Hovered widget, filled during the frame ImGuiID HoveredIdPreviousFrame; @@ -2373,7 +2451,7 @@ struct ImGuiContext ImGuiCol DebugFlashStyleColorIdx; // (Keep close to ColorStack to share cache line) ImVector ColorStack; // Stack for PushStyleColor()/PopStyleColor() - inherited by Begin() ImVector StyleVarStack; // Stack for PushStyleVar()/PopStyleVar() - inherited by Begin() - ImVector FontStack; // Stack for PushFont()/PopFont() - inherited by Begin() + ImVector FontStack; // Stack for PushFont()/PopFont() - inherited by Begin() ImVector FocusScopeStack; // Stack for PushFocusScope()/PopFocusScope() - inherited by BeginChild(), pushed into by Begin() ImVector ItemFlagsStack; // Stack for PushItemFlag()/PopItemFlag() - inherited by Begin() ImVector GroupStack; // Stack for BeginGroup()/EndGroup() - not inherited by Begin() @@ -2404,18 +2482,19 @@ struct ImGuiContext ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusedWindow' ImGuiID NavFocusScopeId; // Focused focus scope (e.g. selection code often wants to "clear other items" when landing on an item of the same scope) ImGuiNavLayer NavLayer; // Focused layer (main scrolling layer, or menu/title bar layer) - ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && (IsKeyPressed(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate)) ? NavId : 0, also set when calling ActivateItem() + ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && (IsKeyPressed(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate)) ? NavId : 0, also set when calling ActivateItemByID() ImGuiID NavActivateDownId; // ~~ IsKeyDown(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyDown(ImGuiKey_NavGamepadActivate) ? NavId : 0 ImGuiID NavActivatePressedId; // ~~ IsKeyPressed(ImGuiKey_Space) || IsKeyPressed(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate) ? NavId : 0 (no repeat) ImGuiActivateFlags NavActivateFlags; ImVector NavFocusRoute; // Reversed copy focus scope stack for NavId (should contains NavFocusScopeId). This essentially follow the window->ParentWindowForFocusRoute chain. ImGuiID NavHighlightActivatedId; float NavHighlightActivatedTimer; - ImGuiID NavNextActivateId; // Set by ActivateItem(), queued until next frame. + ImGuiID NavNextActivateId; // Set by ActivateItemByID(), queued until next frame. ImGuiActivateFlags NavNextActivateFlags; ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS CAN ONLY BE ImGuiInputSource_Keyboard or ImGuiInputSource_Mouse ImGuiSelectionUserData NavLastValidSelectionUserData; // Last valid data passed to SetNextItemSelectionUser(), or -1. For current window. Not reset when focusing an item that doesn't have selection data. ImS8 NavCursorHideFrames; + //ImGuiID NavActivateInputId; // Removed in 1.89.4 (July 2023). This is now part of g.NavActivateId and sets g.NavActivateFlags |= ImGuiActivateFlags_PreferInput. See commit c9a53aa74, issue #5606. // Navigation: Init & Move Requests bool NavAnyRequest; // ~~ NavMoveRequest || NavInitRequest this is to perform early out in ItemAdd() @@ -2450,6 +2529,7 @@ struct ImGuiContext bool NavJustMovedToHasSelectionData; // Copy of move result's ItemFlags & ImGuiItemFlags_HasSelectionUserData). Maybe we should just store ImGuiNavItemData. // Navigation: Windowing (CTRL+TAB for list, or Menu button + keys or directional pads to move/resize) + bool ConfigNavWindowingWithGamepad; // = true. Enable CTRL+TAB by holding ImGuiKey_GamepadFaceLeft (== ImGuiKey_NavGamepadMenu). When false, the button may still be used to toggle Menu layer. ImGuiKeyChord ConfigNavWindowingKeyNext; // = ImGuiMod_Ctrl | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiKey_Tab on OS X). For reconfiguration (see #4828) ImGuiKeyChord ConfigNavWindowingKeyPrev; // = ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab on OS X) ImGuiWindow* NavWindowingTarget; // Target window when doing CTRL+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! @@ -2457,6 +2537,7 @@ struct ImGuiContext ImGuiWindow* NavWindowingListWindow; // Internal window actually listing the CTRL+Tab contents float NavWindowingTimer; float NavWindowingHighlightAlpha; + ImGuiInputSource NavWindowingInputSource; bool NavWindowingToggleLayer; ImGuiKey NavWindowingToggleKey; ImVec2 NavWindowingAccumDeltaPos; @@ -2527,7 +2608,8 @@ struct ImGuiContext // Widget state ImGuiInputTextState InputTextState; ImGuiInputTextDeactivatedState InputTextDeactivatedState; - ImFont InputTextPasswordFont; + ImFontBaked InputTextPasswordFontBackupBaked; + ImFontFlags InputTextPasswordFontBackupFlags; ImGuiID TempInputId; // Temporary text input when CTRL+clicking on a slider, etc. ImGuiDataTypeStorage DataTypeZeroValue; // 0 for all data types int BeginMenuDepth; @@ -2559,12 +2641,12 @@ struct ImGuiContext ImGuiTypingSelectState TypingSelectState; // State for GetTypingSelectRequest() // Platform support - ImGuiPlatformImeData PlatformImeData; // Data updated by current frame + ImGuiPlatformImeData PlatformImeData; // Data updated by current frame. Will be applied at end of the frame. For some backends, this is required to have WantVisible=true in order to receive text message. ImGuiPlatformImeData PlatformImeDataPrev; // Previous frame data. When changed we call the platform_io.Platform_SetImeDataFn() handler. - ImGuiID PlatformImeViewport; // Extensions // FIXME: We could provide an API to register one slot in an array held in ImGuiContext? + ImVector UserTextures; // List of textures created/managed by user or third-party extension. Automatically appended into platform_io.Textures[]. ImGuiDockContext DockContext; void (*DockNodeWindowMenuHandler)(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar); @@ -2626,6 +2708,10 @@ struct ImGuiContext ImGuiIDStackTool DebugIDStackTool; ImGuiDebugAllocInfo DebugAllocInfo; ImGuiDockNode* DebugHoveredDockNode; // Hovered dock node. +#if defined(IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS) && !defined(IMGUI_DISABLE_DEBUG_TOOLS) + ImGuiStorage DebugDrawIdConflictsAliveCount; + ImGuiStorage DebugDrawIdConflictsHighlightSet; +#endif // Misc float FramerateSecPerFrame[60]; // Calculate estimate of framerate for user over the last 60 frames.. @@ -2634,7 +2720,7 @@ struct ImGuiContext float FramerateSecPerFrameAccum; int WantCaptureMouseNextFrame; // Explicit capture override via SetNextFrameWantCaptureMouse()/SetNextFrameWantCaptureKeyboard(). Default to -1. int WantCaptureKeyboardNextFrame; // " - int WantTextInputNextFrame; + int WantTextInputNextFrame; // Copied in EndFrame() from g.PlatformImeData.WantTextInput. Needs to be set for some backends (SDL3) to emit character inputs. ImVector TempBuffer; // Temporary text buffer char TempKeychordName[64]; @@ -2680,7 +2766,8 @@ struct IMGUI_API ImGuiWindowTempData ImVec2 MenuBarOffset; // MenuBarOffset.x is sort of equivalent of a per-layer CursorPos.x, saved/restored as we switch to the menu bar. The only situation when MenuBarOffset.y is > 0 if when (SafeAreaPadding.y > FramePadding.y), often used on TVs. ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items measurement int TreeDepth; // Current tree depth. - ImU32 TreeHasStackDataDepthMask; // Store whether given depth has ImGuiTreeNodeStackData data. Could be turned into a ImU64 if necessary. + ImU32 TreeHasStackDataDepthMask; // Store whether given depth has ImGuiTreeNodeStackData data. Could be turned into a ImU64 if necessary. + ImU32 TreeRecordsClippedNodesY2Mask; // Store whether we should keep recording Y2. Cleared when passing clip max. Equivalent TreeHasStackDataDepthMask value should always be set. ImVector ChildWindows; ImGuiStorage* StateStorage; // Current persistent per-window storage (store e.g. tree node open/close state) ImGuiOldColumns* CurrentColumns; // Current columns set @@ -2800,7 +2887,6 @@ struct IMGUI_API ImGuiWindow ImVector ColumnsStorage; float FontWindowScale; // User scale multiplier per-window, via SetWindowFontScale() float FontWindowScaleParents; - float FontDpiScale; float FontRefSize; // This is a copy of window->CalcFontSize() at the time of Begin(), trying to phase out CalcFontSize() especially as it may be called on non-current window. int SettingsOffset; // Offset into SettingsWindows[] (offsets are always valid as we only grow the array from the back) @@ -2848,9 +2934,11 @@ public: // We don't use g.FontSize because the window may be != g.CurrentWindow. ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } - float CalcFontSize() const { ImGuiContext& g = *Ctx; return g.FontBaseSize * FontWindowScale * FontDpiScale * FontWindowScaleParents; } ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight)); } ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight; return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight); } + + // [Obsolete] ImGuiWindow::CalcFontSize() was removed in 1.92.x because error-prone/misleading. You can use window->FontRefSize for a copy of g.FontSize at the time of the last Begin() call for this window. + //float CalcFontSize() const { ImGuiContext& g = *Ctx; return g.FontSizeBase * FontWindowScale * FontDpiScale * FontWindowScaleParents; }; //----------------------------------------------------------------------------- @@ -2941,11 +3029,7 @@ struct IMGUI_API ImGuiTabBar //----------------------------------------------------------------------------- #define IM_COL32_DISABLE IM_COL32(0,0,0,1) // Special sentinel code which cannot be used as a regular color. -#define IMGUI_TABLE_MAX_COLUMNS 512 // May be further lifted - -// Our current column maximum is 64 but we may raise that in the future. -typedef ImS16 ImGuiTableColumnIdx; -typedef ImU16 ImGuiTableDrawChannelIdx; +#define IMGUI_TABLE_MAX_COLUMNS 512 // Arbitrary "safety" maximum, may be lifted in the future if needed. Must fit in ImGuiTableColumnIdx/ImGuiTableDrawChannelIdx. // [Internal] sizeof() ~ 112 // We use the terminology "Enabled" to refer to a column that is not Hidden by user/api. @@ -3144,7 +3228,7 @@ struct IMGUI_API ImGuiTable bool IsSortSpecsDirty; bool IsUsingHeaders; // Set when the first row had the ImGuiTableRowFlags_Headers flag. bool IsContextPopupOpen; // Set when default context menu is open (also see: ContextPopupColumn, InstanceInteracted). - bool DisableDefaultContextMenu; // Disable default context menu contents. You may submit your own using TableBeginContextMenuPopup()/EndPopup() + bool DisableDefaultContextMenu; // Disable default context menu. You may submit your own using TableBeginContextMenuPopup()/EndPopup() bool IsSettingsRequestLoad; bool IsSettingsDirty; // Set when table settings have changed and needs to be reported into ImGuiTableSetttings data. bool IsDefaultDisplayOrder; // Set when display order is unchanged from default (DisplayOrder contains 0...Count-1) @@ -3278,9 +3362,18 @@ namespace ImGui IMGUI_API void SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags); // Fonts, drawing - IMGUI_API void SetCurrentFont(ImFont* font); - inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } + IMGUI_API void RegisterUserTexture(ImTextureData* tex); // Register external texture + IMGUI_API void UnregisterUserTexture(ImTextureData* tex); + IMGUI_API void RegisterFontAtlas(ImFontAtlas* atlas); + IMGUI_API void UnregisterFontAtlas(ImFontAtlas* atlas); + IMGUI_API void SetCurrentFont(ImFont* font, float font_size_before_scaling, float font_size_after_scaling); + IMGUI_API void UpdateCurrentFontSize(float restore_font_size_after_scaling); + IMGUI_API void SetFontRasterizerDensity(float rasterizer_density); + inline float GetFontRasterizerDensity() { return GImGui->FontRasterizerDensity; } + inline float GetRoundedFontSize(float size) { return IM_ROUND(size); } + IMGUI_API ImFont* GetDefaultFont(); IMGUI_API void PushPasswordFont(); + IMGUI_API void PopPasswordFont(); inline ImDrawList* GetForegroundDrawList(ImGuiWindow* window) { return GetForegroundDrawList(window->Viewport); } IMGUI_API void AddDrawListToDrawDataEx(ImDrawData* draw_data, ImVector* out_list, ImDrawList* draw_list); @@ -3290,7 +3383,7 @@ namespace ImGui // NewFrame IMGUI_API void UpdateInputEvents(bool trickle_fast_inputs); - IMGUI_API void UpdateHoveredWindowAndCaptureFlags(); + IMGUI_API void UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos); IMGUI_API void FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window); IMGUI_API void StartMouseMovingWindow(ImGuiWindow* window); IMGUI_API void StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock); @@ -3422,7 +3515,7 @@ namespace ImGui IMGUI_API void NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags); IMGUI_API void NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags); IMGUI_API void NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result); - IMGUI_API void NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiTreeNodeStackData* tree_node_data); + IMGUI_API void NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, const ImGuiTreeNodeStackData* tree_node_data); IMGUI_API void NavMoveRequestCancel(); IMGUI_API void NavMoveRequestApplyResult(); IMGUI_API void NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags); @@ -3438,7 +3531,7 @@ namespace ImGui // This should be part of a larger set of API: FocusItem(offset = -1), FocusItemByID(id), ActivateItem(offset = -1), ActivateItemByID(id) etc. which are // much harder to design and implement than expected. I have a couple of private branches on this matter but it's not simple. For now implementing the easy ones. IMGUI_API void FocusItem(); // Focus last item (no selection/activation). - IMGUI_API void ActivateItemByID(ImGuiID id); // Activate an item by ID (button, checkbox, tree node etc.). Activation is queued and processed on the next frame when the item is encountered again. + IMGUI_API void ActivateItemByID(ImGuiID id); // Activate an item by ID (button, checkbox, tree node etc.). Activation is queued and processed on the next frame when the item is encountered again. Was called 'ActivateItem()' before 1.89.7. // Inputs // FIXME: Eventually we should aim to move e.g. IsActiveIdUsingKey() into IsKeyXXX functions. @@ -3640,6 +3733,8 @@ namespace ImGui IMGUI_API float TableGetHeaderAngledMaxLabelWidth(); IMGUI_API void TablePushBackgroundChannel(); IMGUI_API void TablePopBackgroundChannel(); + IMGUI_API void TablePushColumnChannel(int column_n); + IMGUI_API void TablePopColumnChannel(); IMGUI_API void TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label_width, const ImGuiTableHeaderData* data, int data_count); // Tables: Internals @@ -3718,7 +3813,7 @@ namespace ImGui IMGUI_API void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width); IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL); IMGUI_API void RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL); - IMGUI_API void RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end, const ImVec2* text_size_if_known); + IMGUI_API void RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float ellipsis_max_x, const char* text, const char* text_end, const ImVec2* text_size_if_known); IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool borders = true, float rounding = 0.0f); IMGUI_API void RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding = 0.0f); IMGUI_API void RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, ImDrawFlags flags = 0); @@ -3739,11 +3834,15 @@ namespace ImGui IMGUI_API void RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const ImRect& inner, ImU32 col, float rounding); IMGUI_API ImDrawFlags CalcRoundingFlagsForRectInRect(const ImRect& r_in, const ImRect& r_outer, float threshold); - // Widgets + // Widgets: Text IMGUI_API void TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0); + IMGUI_API void TextAligned(float align_x, float size_x, const char* fmt, ...); // FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024) + IMGUI_API void TextAlignedV(float align_x, float size_x, const char* fmt, va_list args); + + // Widgets IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags = 0); - IMGUI_API bool ImageButtonEx(ImGuiID id, ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags = 0); + IMGUI_API bool ImageButtonEx(ImGuiID id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags = 0); IMGUI_API void SeparatorEx(ImGuiSeparatorFlags flags, float thickness = 1.0f); IMGUI_API void SeparatorTextEx(ImGuiID id, const char* label, const char* label_end, float extra_width); IMGUI_API bool CheckboxFlags(const char* label, ImS64* flags, ImS64 flags_value); @@ -3767,6 +3866,8 @@ namespace ImGui // Widgets: Tree Nodes IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); + IMGUI_API void TreeNodeDrawLineToChildNode(const ImVec2& target_pos); + IMGUI_API void TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data); IMGUI_API void TreePushOverrideID(ImGuiID id); IMGUI_API bool TreeNodeGetOpen(ImGuiID storage_id); IMGUI_API void TreeNodeSetOpen(ImGuiID storage_id, bool open); @@ -3848,7 +3949,9 @@ namespace ImGui IMGUI_API void DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label); IMGUI_API void DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb); IMGUI_API void DebugNodeFont(ImFont* font); + IMGUI_API void DebugNodeFontGlyphesForSrcMask(ImFont* font, ImFontBaked* baked, int src_mask); IMGUI_API void DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph); + IMGUI_API void DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRect* highlight_rect = NULL); // ID used to facilitate persisting the "current" texture. IMGUI_API void DebugNodeStorage(ImGuiStorage* storage, const char* label); IMGUI_API void DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label); IMGUI_API void DebugNodeTable(ImGuiTable* table); @@ -3871,6 +3974,7 @@ namespace ImGui //inline bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0) { return TreeNodeUpdateNextOpen(id, flags); } // Renamed in 1.89 //inline bool IsKeyPressedMap(ImGuiKey key, bool repeat = true) { IM_ASSERT(IsNamedKey(key)); return IsKeyPressed(key, repeat); } // Removed in 1.87: Mapping from named key is always identity! + // Refactored focus/nav/tabbing system in 1.82 and 1.84. If you have old/custom copy-and-pasted widgets which used FocusableItemRegister(): // Refactored focus/nav/tabbing system in 1.82 and 1.84. If you have old/custom copy-and-pasted widgets which used FocusableItemRegister(): // (Old) IMGUI_VERSION_NUM < 18209: using 'ItemAdd(....)' and 'bool tab_focused = FocusableItemRegister(...)' // (Old) IMGUI_VERSION_NUM >= 18209: using 'ItemAdd(..., ImGuiItemAddFlags_Focusable)' and 'bool tab_focused = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Focused) != 0' @@ -3882,31 +3986,192 @@ namespace ImGui } // namespace ImGui +//----------------------------------------------------------------------------- +// [SECTION] ImFontLoader +//----------------------------------------------------------------------------- + +// Hooks and storage for a given font backend. +// This structure is likely to evolve as we add support for incremental atlas updates. +// Conceptually this could be public, but API is still going to be evolve. +struct ImFontLoader +{ + const char* Name; + bool (*LoaderInit)(ImFontAtlas* atlas); + void (*LoaderShutdown)(ImFontAtlas* atlas); + bool (*FontSrcInit)(ImFontAtlas* atlas, ImFontConfig* src); + void (*FontSrcDestroy)(ImFontAtlas* atlas, ImFontConfig* src); + bool (*FontSrcContainsGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint); + bool (*FontBakedInit)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); + void (*FontBakedDestroy)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); + bool (*FontBakedLoadGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x); + + // Size of backend data, Per Baked * Per Source. Buffers are managed by core to avoid excessive allocations. + // FIXME: At this point the two other types of buffers may be managed by core to be consistent? + size_t FontBakedSrcLoaderDataSize; + + ImFontLoader() { memset(this, 0, sizeof(*this)); } +}; + +#ifdef IMGUI_ENABLE_STB_TRUETYPE +IMGUI_API const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype(); +#endif +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +typedef ImFontLoader ImFontBuilderIO; // [renamed/changed in 1.92] The types are not actually compatible but we provide this as a compile-time error report helper. +#endif + //----------------------------------------------------------------------------- // [SECTION] ImFontAtlas internal API //----------------------------------------------------------------------------- -// This structure is likely to evolve as we add support for incremental atlas updates. -// Conceptually this could be in ImGuiPlatformIO, but we are far from ready to make this public. -struct ImFontBuilderIO +#define IMGUI_FONT_SIZE_MAX (512.0f) +#define IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE (128.0f) + +// Helpers: ImTextureRef ==/!= operators provided as convenience +// (note that _TexID and _TexData are never set simultaneously) +inline bool operator==(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID == rhs._TexID && lhs._TexData == rhs._TexData; } +inline bool operator!=(const ImTextureRef& lhs, const ImTextureRef& rhs) { return lhs._TexID != rhs._TexID || lhs._TexData != rhs._TexData; } + +// Refer to ImFontAtlasPackGetRect() to better understand how this works. +#define ImFontAtlasRectId_IndexMask_ (0x000FFFFF) // 20-bits: index to access builder->RectsIndex[]. +#define ImFontAtlasRectId_GenerationMask_ (0x3FF00000) // 10-bits: entry generation, so each ID is unique and get can safely detected old identifiers. +#define ImFontAtlasRectId_GenerationShift_ (20) +inline int ImFontAtlasRectId_GetIndex(ImFontAtlasRectId id) { return id & ImFontAtlasRectId_IndexMask_; } +inline int ImFontAtlasRectId_GetGeneration(ImFontAtlasRectId id) { return (id & ImFontAtlasRectId_GenerationMask_) >> ImFontAtlasRectId_GenerationShift_; } +inline ImFontAtlasRectId ImFontAtlasRectId_Make(int index_idx, int gen_idx) { IM_ASSERT(index_idx < ImFontAtlasRectId_IndexMask_ && gen_idx < (ImFontAtlasRectId_GenerationMask_ >> ImFontAtlasRectId_GenerationShift_)); return (ImFontAtlasRectId)(index_idx | (gen_idx << ImFontAtlasRectId_GenerationShift_)); } + +// Packed rectangle lookup entry (we need an indirection to allow removing/reordering rectangles) +// User are returned ImFontAtlasRectId values which are meant to be persistent. +// We handle this with an indirection. While Rects[] may be in theory shuffled, compacted etc., RectsIndex[] cannot it is keyed by ImFontAtlasRectId. +// RectsIndex[] is used both as an index into Rects[] and an index into itself. This is basically a free-list. See ImFontAtlasBuildAllocRectIndexEntry() code. +// Having this also makes it easier to e.g. sort rectangles during repack. +struct ImFontAtlasRectEntry { - bool (*FontBuilder_Build)(ImFontAtlas* atlas); + int TargetIndex : 20; // When Used: ImFontAtlasRectId -> into Rects[]. When unused: index to next unused RectsIndex[] slot to consume free-list. + int Generation : 10; // Increased each time the entry is reused for a new rectangle. + unsigned int IsUsed : 1; }; -// Helper for font builder -#ifdef IMGUI_ENABLE_STB_TRUETYPE -IMGUI_API const ImFontBuilderIO* ImFontAtlasGetBuilderForStbTruetype(); +// Data available to potential texture post-processing functions +struct ImFontAtlasPostProcessData +{ + ImFontAtlas* FontAtlas; + ImFont* Font; + ImFontConfig* FontSrc; + ImFontBaked* FontBaked; + ImFontGlyph* Glyph; + + // Pixel data + void* Pixels; + ImTextureFormat Format; + int Pitch; + int Width; + int Height; +}; + +// We avoid dragging imstb_rectpack.h into public header (partly because binding generators are having issues with it) +#ifdef IMGUI_STB_NAMESPACE +namespace IMGUI_STB_NAMESPACE { struct stbrp_node; } +typedef IMGUI_STB_NAMESPACE::stbrp_node stbrp_node_im; +#else +struct stbrp_node; +typedef stbrp_node stbrp_node_im; +#endif +struct stbrp_context_opaque { char data[80]; }; + +// Internal storage for incrementally packing and building a ImFontAtlas +struct ImFontAtlasBuilder +{ + stbrp_context_opaque PackContext; // Actually 'stbrp_context' but we don't want to define this in the header file. + ImVector PackNodes; + ImVector Rects; + ImVector RectsIndex; // ImFontAtlasRectId -> index into Rects[] + ImVector TempBuffer; // Misc scratch buffer + int RectsIndexFreeListStart;// First unused entry + int RectsPackedCount; // Number of packed rectangles. + int RectsPackedSurface; // Number of packed pixels. Used when compacting to heuristically find the ideal texture size. + int RectsDiscardedCount; + int RectsDiscardedSurface; + int FrameCount; // Current frame count + ImVec2i MaxRectSize; // Largest rectangle to pack (de-facto used as a "minimum texture size") + ImVec2i MaxRectBounds; // Bottom-right most used pixels + bool LockDisableResize; // Disable resizing texture + bool PreloadedAllGlyphsRanges; // Set when missing ImGuiBackendFlags_RendererHasTextures features forces atlas to preload everything. + + // Cache of all ImFontBaked + ImStableVector BakedPool; + ImGuiStorage BakedMap; // BakedId --> ImFontBaked* + int BakedDiscardedCount; + + // Custom rectangle identifiers + ImFontAtlasRectId PackIdMouseCursors; // White pixel + mouse cursors. Also happen to be fallback in case of packing failure. + ImFontAtlasRectId PackIdLinesTexData; + + ImFontAtlasBuilder() { memset(this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = -1; } +}; + +IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildDestroy(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildMain(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* font_loader); +IMGUI_API void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char); +IMGUI_API void ImFontAtlasBuildClear(ImFontAtlas* atlas); // Clear output and custom rects + +IMGUI_API ImTextureData* ImFontAtlasTextureAdd(ImFontAtlas* atlas, int w, int h); +IMGUI_API void ImFontAtlasTextureMakeSpace(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasTextureRepack(ImFontAtlas* atlas, int w, int h); +IMGUI_API void ImFontAtlasTextureGrow(ImFontAtlas* atlas, int old_w = -1, int old_h = -1); +IMGUI_API void ImFontAtlasTextureCompact(ImFontAtlas* atlas); +IMGUI_API ImVec2i ImFontAtlasTextureGetSizeEstimate(ImFontAtlas* atlas); + +IMGUI_API void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); +IMGUI_API void ImFontAtlasBuildLegacyPreloadAllGlyphRanges(ImFontAtlas* atlas); // Legacy +IMGUI_API void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, ImFontBaked* baked, int* out_oversample_h, int* out_oversample_v); +IMGUI_API void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames); + +IMGUI_API bool ImFontAtlasFontSourceInit(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API void ImFontAtlasFontSourceAddToFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src); +IMGUI_API void ImFontAtlasFontDestroySourceData(ImFontAtlas* atlas, ImFontConfig* src); +IMGUI_API bool ImFontAtlasFontInitOutput(ImFontAtlas* atlas, ImFont* font); // Using FontDestroyOutput/FontInitOutput sequence useful notably if font loader params have changed +IMGUI_API void ImFontAtlasFontDestroyOutput(ImFontAtlas* atlas, ImFont* font); +IMGUI_API void ImFontAtlasFontDiscardBakes(ImFontAtlas* atlas, ImFont* font, int unused_frames); + +IMGUI_API ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size, float rasterizer_density); +IMGUI_API ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density); +IMGUI_API ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density); +IMGUI_API ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density, ImGuiID baked_id); +IMGUI_API void ImFontAtlasBakedDiscard(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked); +IMGUI_API ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph); +IMGUI_API void ImFontAtlasBakedAddFontGlyphAdvancedX(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImWchar codepoint, float advance_x); +IMGUI_API void ImFontAtlasBakedDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph); +IMGUI_API void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImTextureRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch); + +IMGUI_API void ImFontAtlasPackInit(ImFontAtlas* atlas); +IMGUI_API ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry = NULL); +IMGUI_API ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id); +IMGUI_API ImTextureRect* ImFontAtlasPackGetRectSafe(ImFontAtlas* atlas, ImFontAtlasRectId id); +IMGUI_API void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id); + +IMGUI_API void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count, bool renderer_has_textures); +IMGUI_API void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data); +IMGUI_API void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data); +IMGUI_API void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex, ImTextureRef new_tex); +IMGUI_API void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas); + +IMGUI_API void ImFontAtlasTextureBlockConvert(const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch, unsigned char* dst_pixels, ImTextureFormat dst_fmt, int dst_pitch, int w, int h); +IMGUI_API void ImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data); +IMGUI_API void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data, float multiply_factor); +IMGUI_API void ImFontAtlasTextureBlockFill(ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h, ImU32 col); +IMGUI_API void ImFontAtlasTextureBlockCopy(ImTextureData* src_tex, int src_x, int src_y, ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h); +IMGUI_API void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, int x, int y, int w, int h); + +IMGUI_API int ImTextureDataGetFormatBytesPerPixel(ImTextureFormat format); +IMGUI_API const char* ImTextureDataGetStatusName(ImTextureStatus status); +IMGUI_API const char* ImTextureDataGetFormatName(ImTextureFormat format); + +#ifndef IMGUI_DISABLE_DEBUG_TOOLS +IMGUI_API void ImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas); #endif -IMGUI_API void ImFontAtlasUpdateSourcesPointers(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src, float ascent, float descent); -IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque); -IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasBuildRender8bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned char in_marker_pixel_value); -IMGUI_API void ImFontAtlasBuildRender32bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned int in_marker_pixel_value); -IMGUI_API void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_multiply_factor); -IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride); -IMGUI_API void ImFontAtlasBuildGetOversampleFactors(const ImFontConfig* src, int* out_oversample_h, int* out_oversample_v); IMGUI_API bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]); diff --git a/lib/third_party/imgui/imgui/include/imstb_textedit.h b/lib/third_party/imgui/imgui/include/imstb_textedit.h index b7a761c85..33eef7095 100644 --- a/lib/third_party/imgui/imgui/include/imstb_textedit.h +++ b/lib/third_party/imgui/imgui/include/imstb_textedit.h @@ -141,6 +141,7 @@ // with previous char) // STB_TEXTEDIT_KEYTOTEXT(k) maps a keyboard input to an insertable character // (return type is int, -1 means not valid to insert) +// (not supported if you want to use UTF-8, see below) // STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 0-based // STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize // as manually wordwrapping for end-of-line positioning @@ -178,6 +179,13 @@ // STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text // STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text // +// To support UTF-8: +// +// STB_TEXTEDIT_GETPREVCHARINDEX returns index of previous character +// STB_TEXTEDIT_GETNEXTCHARINDEX returns index of next character +// Do NOT define STB_TEXTEDIT_KEYTOTEXT. +// Instead, call stb_textedit_text() directly for text contents. +// // Keyboard input must be encoded as a single integer value; e.g. a character code // and some bitflags that represent shift states. to simplify the interface, SHIFT must // be a bitflag, so we can test the shifted state of cursor movements to allow selection, @@ -250,8 +258,10 @@ // if the STB_TEXTEDIT_KEYTOTEXT function is defined, selected keys are // transformed into text and stb_textedit_text() is automatically called. // -// text: [DEAR IMGUI] added 2024-09 -// call this to text inputs sent to the textfield. +// text: (added 2025) +// call this to directly send text input the textfield, which is required +// for UTF-8 support, because stb_textedit_key() + STB_TEXTEDIT_KEYTOTEXT() +// cannot infer text length. // // // When rendering, you can read the cursor position and selection state from @@ -400,6 +410,16 @@ typedef struct #define IMSTB_TEXTEDIT_memmove memmove #endif +// [DEAR IMGUI] +// Functions must be implemented for UTF8 support +// Code in this file that uses those functions is modified for [DEAR IMGUI] and deviates from the original stb_textedit. +// There is not necessarily a '[DEAR IMGUI]' at the usage sites. +#ifndef IMSTB_TEXTEDIT_GETPREVCHARINDEX +#define IMSTB_TEXTEDIT_GETPREVCHARINDEX(OBJ, IDX) ((IDX) - 1) +#endif +#ifndef IMSTB_TEXTEDIT_GETNEXTCHARINDEX +#define IMSTB_TEXTEDIT_GETNEXTCHARINDEX(OBJ, IDX) ((IDX) + 1) +#endif ///////////////////////////////////////////////////////////////////////////// // @@ -648,17 +668,6 @@ static void stb_textedit_move_to_last(IMSTB_TEXTEDIT_STRING *str, STB_TexteditSt } } -// [DEAR IMGUI] -// Functions must be implemented for UTF8 support -// Code in this file that uses those functions is modified for [DEAR IMGUI] and deviates from the original stb_textedit. -// There is not necessarily a '[DEAR IMGUI]' at the usage sites. -#ifndef IMSTB_TEXTEDIT_GETPREVCHARINDEX -#define IMSTB_TEXTEDIT_GETPREVCHARINDEX(obj, idx) (idx - 1) -#endif -#ifndef IMSTB_TEXTEDIT_GETNEXTCHARINDEX -#define IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx) (idx + 1) -#endif - #ifdef STB_TEXTEDIT_IS_SPACE static int is_word_boundary( IMSTB_TEXTEDIT_STRING *str, int idx ) { @@ -668,9 +677,9 @@ static int is_word_boundary( IMSTB_TEXTEDIT_STRING *str, int idx ) #ifndef STB_TEXTEDIT_MOVEWORDLEFT static int stb_textedit_move_to_word_previous( IMSTB_TEXTEDIT_STRING *str, int c ) { - --c; // always move at least one character - while( c >= 0 && !is_word_boundary( str, c ) ) - --c; + c = IMSTB_TEXTEDIT_GETPREVCHARINDEX( str, c ); // always move at least one character + while (c >= 0 && !is_word_boundary(str, c)) + c = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, c); if( c < 0 ) c = 0; @@ -684,9 +693,9 @@ static int stb_textedit_move_to_word_previous( IMSTB_TEXTEDIT_STRING *str, int c static int stb_textedit_move_to_word_next( IMSTB_TEXTEDIT_STRING *str, int c ) { const int len = STB_TEXTEDIT_STRINGLEN(str); - ++c; // always move at least one character + c = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, c); // always move at least one character while( c < len && !is_word_boundary( str, c ) ) - ++c; + c = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, c); if( c > len ) c = len; @@ -739,6 +748,7 @@ static int stb_textedit_paste_internal(IMSTB_TEXTEDIT_STRING *str, STB_TexteditS #define STB_TEXTEDIT_KEYTYPE int #endif +// API key: process text input // [DEAR IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility. static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* state, const IMSTB_TEXTEDIT_CHARTYPE* text, int text_len) { @@ -753,8 +763,7 @@ static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* sta state->cursor += text_len; state->has_preferred_x = 0; } - } - else { + } else { stb_textedit_delete_selection(str, state); // implicitly clamps if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, text_len)) { stb_text_makeundo_insert(state, state->cursor, text_len); @@ -771,6 +780,7 @@ retry: switch (key) { default: { #ifdef STB_TEXTEDIT_KEYTOTEXT + // This is not suitable for UTF-8 support. int c = STB_TEXTEDIT_KEYTOTEXT(key); if (c > 0) { IMSTB_TEXTEDIT_CHARTYPE ch = (IMSTB_TEXTEDIT_CHARTYPE)c; @@ -918,8 +928,9 @@ retry: state->cursor = start; STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); x = row.x0; - for (i=0; i < row.num_chars; ++i) { + for (i=0; i < row.num_chars; ) { float dx = STB_TEXTEDIT_GETWIDTH(str, start, i); + int next = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); #ifdef IMSTB_TEXTEDIT_GETWIDTH_NEWLINE if (dx == IMSTB_TEXTEDIT_GETWIDTH_NEWLINE) break; @@ -927,7 +938,8 @@ retry: x += dx; if (x > goal_x) break; - state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); + i += next - state->cursor; + state->cursor = next; } stb_textedit_clamp(str, state); @@ -980,8 +992,9 @@ retry: state->cursor = find.prev_first; STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); x = row.x0; - for (i=0; i < row.num_chars; ++i) { + for (i=0; i < row.num_chars; ) { float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i); + int next = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); #ifdef IMSTB_TEXTEDIT_GETWIDTH_NEWLINE if (dx == IMSTB_TEXTEDIT_GETWIDTH_NEWLINE) break; @@ -989,7 +1002,8 @@ retry: x += dx; if (x > goal_x) break; - state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); + i += next - state->cursor; + state->cursor = next; } stb_textedit_clamp(str, state); @@ -1002,8 +1016,13 @@ retry: // go to previous line // (we need to scan previous line the hard way. maybe we could expose this as a new API function?) prev_scan = find.prev_first > 0 ? find.prev_first - 1 : 0; - while (prev_scan > 0 && STB_TEXTEDIT_GETCHAR(str, prev_scan - 1) != STB_TEXTEDIT_NEWLINE) - --prev_scan; + while (prev_scan > 0) + { + int prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, prev_scan); + if (STB_TEXTEDIT_GETCHAR(str, prev) == STB_TEXTEDIT_NEWLINE) + break; + prev_scan = prev; + } find.first_char = find.prev_first; find.prev_first = prev_scan; } @@ -1082,7 +1101,7 @@ retry: if (state->single_line) state->cursor = 0; else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) - --state->cursor; + state->cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); state->has_preferred_x = 0; break; @@ -1094,9 +1113,9 @@ retry: stb_textedit_clamp(str, state); stb_textedit_move_to_first(state); if (state->single_line) - state->cursor = n; + state->cursor = n; else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) - ++state->cursor; + state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); state->has_preferred_x = 0; break; } @@ -1110,7 +1129,7 @@ retry: if (state->single_line) state->cursor = 0; else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) - --state->cursor; + state->cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state->cursor); state->select_end = state->cursor; state->has_preferred_x = 0; break; @@ -1125,7 +1144,7 @@ retry: if (state->single_line) state->cursor = n; else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) - ++state->cursor; + state->cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state->cursor); state->select_end = state->cursor; state->has_preferred_x = 0; break; diff --git a/lib/third_party/imgui/imgui/include/imstb_truetype.h b/lib/third_party/imgui/imgui/include/imstb_truetype.h index 976f09cb9..cf33289f6 100644 --- a/lib/third_party/imgui/imgui/include/imstb_truetype.h +++ b/lib/third_party/imgui/imgui/include/imstb_truetype.h @@ -4516,8 +4516,8 @@ static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex q2[0] = (float)x2; q2[1] = (float)y2; if (equal(q0,q1) || equal(q1,q2)) { - x0 = (int)verts[i-1].x; - y0 = (int)verts[i-1].y; + x0 = (int)verts[i-1].x; //-V1048 + y0 = (int)verts[i-1].y; //-V1048 x1 = (int)verts[i ].x; y1 = (int)verts[i ].y; if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { diff --git a/lib/third_party/imgui/imgui/include/misc/freetype/imgui_freetype.h b/lib/third_party/imgui/imgui/include/misc/freetype/imgui_freetype.h index d8c8444b0..5cca324d7 100644 --- a/lib/third_party/imgui/imgui/include/misc/freetype/imgui_freetype.h +++ b/lib/third_party/imgui/imgui/include/misc/freetype/imgui_freetype.h @@ -6,7 +6,9 @@ #ifndef IMGUI_DISABLE // Usage: -// - Add '#define IMGUI_ENABLE_FREETYPE' in your imconfig to enable support for imgui_freetype in imgui. +// - Add '#define IMGUI_ENABLE_FREETYPE' in your imconfig to automatically enable support +// for imgui_freetype in imgui. It is equivalent to selecting the default loader with: +// io.Fonts->SetFontLoader(ImGuiFreeType::GetFontLoader()) // Optional support for OpenType SVG fonts: // - Add '#define IMGUI_ENABLE_FREETYPE_PLUTOSVG' to use plutosvg (not provided). See #7927. @@ -14,46 +16,70 @@ // Forward declarations struct ImFontAtlas; -struct ImFontBuilderIO; +struct ImFontLoader; // Hinting greatly impacts visuals (and glyph sizes). // - By default, hinting is enabled and the font's native hinter is preferred over the auto-hinter. // - When disabled, FreeType generates blurrier glyphs, more or less matches the stb_truetype.h // - The Default hinting mode usually looks good, but may distort glyphs in an unusual way. // - The Light hinting mode generates fuzzier glyphs but better matches Microsoft's rasterizer. -// You can set those flags globaly in ImFontAtlas::FontBuilderFlags -// You can set those flags on a per font basis in ImFontConfig::FontBuilderFlags -enum ImGuiFreeTypeBuilderFlags +// You can set those flags globally in ImFontAtlas::FontLoaderFlags +// You can set those flags on a per font basis in ImFontConfig::FontLoaderFlags +typedef unsigned int ImGuiFreeTypeLoaderFlags; +enum ImGuiFreeTypeLoaderFlags_ { - ImGuiFreeTypeBuilderFlags_NoHinting = 1 << 0, // Disable hinting. This generally generates 'blurrier' bitmap glyphs when the glyph are rendered in any of the anti-aliased modes. - ImGuiFreeTypeBuilderFlags_NoAutoHint = 1 << 1, // Disable auto-hinter. - ImGuiFreeTypeBuilderFlags_ForceAutoHint = 1 << 2, // Indicates that the auto-hinter is preferred over the font's native hinter. - ImGuiFreeTypeBuilderFlags_LightHinting = 1 << 3, // A lighter hinting algorithm for gray-level modes. Many generated glyphs are fuzzier but better resemble their original shape. This is achieved by snapping glyphs to the pixel grid only vertically (Y-axis), as is done by Microsoft's ClearType and Adobe's proprietary font renderer. This preserves inter-glyph spacing in horizontal text. - ImGuiFreeTypeBuilderFlags_MonoHinting = 1 << 4, // Strong hinting algorithm that should only be used for monochrome output. - ImGuiFreeTypeBuilderFlags_Bold = 1 << 5, // Styling: Should we artificially embolden the font? - ImGuiFreeTypeBuilderFlags_Oblique = 1 << 6, // Styling: Should we slant the font, emulating italic style? - ImGuiFreeTypeBuilderFlags_Monochrome = 1 << 7, // Disable anti-aliasing. Combine this with MonoHinting for best results! - ImGuiFreeTypeBuilderFlags_LoadColor = 1 << 8, // Enable FreeType color-layered glyphs - ImGuiFreeTypeBuilderFlags_Bitmap = 1 << 9, // Enable FreeType bitmap glyphs - ImGuiFreeTypeBuilderFlags_SubPixel = 1 << 10 // Atlas was generated with sub-pixel rendering enabled + ImGuiFreeTypeLoaderFlags_NoHinting = 1 << 0, // Disable hinting. This generally generates 'blurrier' bitmap glyphs when the glyph are rendered in any of the anti-aliased modes. + ImGuiFreeTypeLoaderFlags_NoAutoHint = 1 << 1, // Disable auto-hinter. + ImGuiFreeTypeLoaderFlags_ForceAutoHint = 1 << 2, // Indicates that the auto-hinter is preferred over the font's native hinter. + ImGuiFreeTypeLoaderFlags_LightHinting = 1 << 3, // A lighter hinting algorithm for gray-level modes. Many generated glyphs are fuzzier but better resemble their original shape. This is achieved by snapping glyphs to the pixel grid only vertically (Y-axis), as is done by Microsoft's ClearType and Adobe's proprietary font renderer. This preserves inter-glyph spacing in horizontal text. + ImGuiFreeTypeLoaderFlags_MonoHinting = 1 << 4, // Strong hinting algorithm that should only be used for monochrome output. + ImGuiFreeTypeLoaderFlags_Bold = 1 << 5, // Styling: Should we artificially embolden the font? + ImGuiFreeTypeLoaderFlags_Oblique = 1 << 6, // Styling: Should we slant the font, emulating italic style? + ImGuiFreeTypeLoaderFlags_Monochrome = 1 << 7, // Disable anti-aliasing. Combine this with MonoHinting for best results! + ImGuiFreeTypeLoaderFlags_LoadColor = 1 << 8, // Enable FreeType color-layered glyphs + ImGuiFreeTypeLoaderFlags_Bitmap = 1 << 9, // Enable FreeType bitmap glyphs + // IMHEX PATCH BEGIN + ImGuiFreeTypeLoaderFlags_SubPixel = 1 << 10 // Atlas was generated with sub-pixel rendering enabled + // IMHEX PATCH END +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiFreeTypeBuilderFlags_NoHinting = ImGuiFreeTypeLoaderFlags_NoHinting, + ImGuiFreeTypeBuilderFlags_NoAutoHint = ImGuiFreeTypeLoaderFlags_NoAutoHint, + ImGuiFreeTypeBuilderFlags_ForceAutoHint = ImGuiFreeTypeLoaderFlags_ForceAutoHint, + ImGuiFreeTypeBuilderFlags_LightHinting = ImGuiFreeTypeLoaderFlags_LightHinting, + ImGuiFreeTypeBuilderFlags_MonoHinting = ImGuiFreeTypeLoaderFlags_MonoHinting, + ImGuiFreeTypeBuilderFlags_Bold = ImGuiFreeTypeLoaderFlags_Bold, + ImGuiFreeTypeBuilderFlags_Oblique = ImGuiFreeTypeLoaderFlags_Oblique, + ImGuiFreeTypeBuilderFlags_Monochrome = ImGuiFreeTypeLoaderFlags_Monochrome, + ImGuiFreeTypeBuilderFlags_LoadColor = ImGuiFreeTypeLoaderFlags_LoadColor, + ImGuiFreeTypeBuilderFlags_Bitmap = ImGuiFreeTypeLoaderFlags_Bitmap, +#endif }; +// Obsolete names (will be removed) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +typedef ImGuiFreeTypeLoaderFlags_ ImGuiFreeTypeBuilderFlags_; +#endif + namespace ImGuiFreeType { // This is automatically assigned when using '#define IMGUI_ENABLE_FREETYPE'. // If you need to dynamically select between multiple builders: - // - you can manually assign this builder with 'atlas->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType()' - // - prefer deep-copying this into your own ImFontBuilderIO instance if you use hot-reloading that messes up static data. - IMGUI_API const ImFontBuilderIO* GetBuilderForFreeType(); + // - you can manually assign this builder with 'atlas->SetFontLoader(ImGuiFreeType::GetFontLoader())' + // - prefer deep-copying this into your own ImFontLoader instance if you use hot-reloading that messes up static data. + IMGUI_API const ImFontLoader* GetFontLoader(); // Override allocators. By default ImGuiFreeType will use IM_ALLOC()/IM_FREE() // However, as FreeType does lots of allocations we provide a way for the user to redirect it to a separate memory heap if desired. IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data = nullptr); - // Obsolete names (will be removed soon) + // Display UI to edit ImFontAtlas::FontLoaderFlags (shared) or ImFontConfig::FontLoaderFlags (single source) + IMGUI_API bool DebugEditFontLoaderFlags(ImGuiFreeTypeLoaderFlags* p_font_loader_flags); + + // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - //static inline bool BuildFontAtlas(ImFontAtlas* atlas, unsigned int flags = 0) { atlas->FontBuilderIO = GetBuilderForFreeType(); atlas->FontBuilderFlags = flags; return atlas->Build(); } // Prefer using '#define IMGUI_ENABLE_FREETYPE' + //IMGUI_API const ImFontBuilderIO* GetBuilderForFreeType(); // Renamed/changed in 1.92. Change 'io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType()' to 'io.Fonts->SetFontLoader(ImGuiFreeType::GetFontLoader())' if you need runtime selection. + //static inline bool BuildFontAtlas(ImFontAtlas* atlas, unsigned int flags = 0) { atlas->FontBuilderIO = GetBuilderForFreeType(); atlas->FontLoaderFlags = flags; return atlas->Build(); } // Prefer using '#define IMGUI_ENABLE_FREETYPE' #endif } diff --git a/lib/third_party/imgui/imgui/source/imgui.cpp b/lib/third_party/imgui/imgui/source/imgui.cpp index 2b47fd0fe..16aa77e0f 100644 --- a/lib/third_party/imgui/imgui/source/imgui.cpp +++ b/lib/third_party/imgui/imgui/source/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9b +// dear imgui, v1.92.1 // (main code and documentation) // Help: @@ -21,9 +21,10 @@ // - Issues & support ........... https://github.com/ocornut/imgui/issues // - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps) -// For first-time users having issues compiling/linking/running/loading fonts: +// For first-time users having issues compiling/linking/running: // please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above. // Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there. +// Since 1.92, we encourage font loading question to also be posted in 'Issues'. // Copyright (c) 2014-2025 Omar Cornut // Developed by Omar Cornut and every direct or indirect contributors to the GitHub. @@ -52,7 +53,7 @@ DOCUMENTATION - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE - HOW A SIMPLE APPLICATION MAY LOOK LIKE - - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE + - USING CUSTOM BACKEND / CUSTOM ENGINE - API BREAKING CHANGES (read me when you update!) - FREQUENTLY ASKED QUESTIONS (FAQ) - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer) @@ -77,6 +78,7 @@ CODE // [SECTION] RENDER HELPERS // [SECTION] INITIALIZATION, SHUTDOWN // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!) +// [SECTION] FONTS // [SECTION] ID STACK // [SECTION] INPUTS // [SECTION] ERROR CHECKING, STATE RECOVERY @@ -273,7 +275,8 @@ CODE HOW A SIMPLE APPLICATION MAY LOOK LIKE -------------------------------------- - EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder). + + USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder). The sub-folders in examples/ contain examples applications following this structure. // Application init: create a dear imgui context, setup some options, load fonts @@ -298,7 +301,7 @@ CODE // Any application code here ImGui::Text("Hello, world!"); - // Render dear imgui into screen + // Render dear imgui into framebuffer ImGui::Render(); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); g_pSwapChain->Present(1, 0); @@ -309,26 +312,36 @@ CODE ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); - EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE + To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application, + you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags! + Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this. - // Application init: create a dear imgui context, setup some options, load fonts + +USING CUSTOM BACKEND / CUSTOM ENGINE +------------------------------------ + +IMPLEMENTING YOUR PLATFORM BACKEND: + -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for basic instructions. + -> the Platform backends in impl_impl_XXX.cpp files contain many implementations. + +IMPLEMENTING YOUR RenderDrawData() function: + -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md + -> the Renderer Backends in impl_impl_XXX.cpp files contain many implementations of a ImGui_ImplXXXX_RenderDrawData() function. + +IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: + -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md + -> the Renderer Backends in impl_impl_XXX.cpp files contain many implementations of a ImGui_ImplXXXX_UpdateTexture() function. + + Basic application/backend skeleton: + + // Application init: create a Dear ImGui context, setup some options, load fonts ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); - // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls. - // TODO: Fill optional fields of the io structure later. + // TODO: set io.ConfigXXX values, e.g. + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable keyboard controls + // TODO: Load TTF/OTF fonts if you don't want to use the default font. - - // Build and load the texture atlas into a texture - // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer) - int width, height; - unsigned char* pixels = nullptr; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); - - // At this point you've got the texture data and you need to upload that to your graphic system: - // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'. - // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID. - MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32) - io.Fonts->SetTexID((void*)texture); + io.Fonts->AddFontFromFileTTF("NotoSans.ttf"); // Application main loop while (true) @@ -351,77 +364,25 @@ CODE MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End(); MyGameRender(); // may use any Dear ImGui functions as well! - // Render dear imgui, swap buffers + // End the dear imgui frame // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code) - ImGui::EndFrame(); + ImGui::EndFrame(); // this is automatically called by Render(), but available ImGui::Render(); + + // Update textures ImDrawData* draw_data = ImGui::GetDrawData(); - MyImGuiRenderFunction(draw_data); + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + MyImGuiBackend_UpdateTexture(tex); + + // Render dear imgui contents, swap buffers + MyImGuiBackend_RenderDrawData(draw_data); SwapBuffers(); } // Shutdown ImGui::DestroyContext(); - To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application, - you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags! - Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this. - - - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE - --------------------------------------------- - The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function. - - void MyImGuiRenderFunction(ImDrawData* draw_data) - { - // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled - // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering. - // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize - // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize - // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color. - ImVec2 clip_off = draw_data->DisplayPos; - for (int n = 0; n < draw_data->CmdListsCount; n++) - { - const ImDrawList* cmd_list = draw_data->CmdLists[n]; - const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui - const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui - for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) - { - const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback) - { - pcmd->UserCallback(cmd_list, pcmd); - } - else - { - // Project scissor/clipping rectangles into framebuffer space - ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y); - ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y); - if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) - continue; - - // We are using scissoring to clip some objects. All low-level graphics API should support it. - // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches - // (some elements visible outside their bounds) but you can fix that once everything else works! - // - Clipping coordinates are provided in imgui coordinates space: - // - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size - // - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values. - // - In the interest of supporting multi-viewport applications (see 'docking' branch on github), - // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space. - // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min) - MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y); - - // The texture for the draw call is specified by pcmd->GetTexID(). - // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization. - MyEngineBindTexture((MyTexture*)pcmd->GetTexID()); - - // Render 'pcmd->ElemCount/3' indexed triangles. - // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices. - MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset); - } - } - } - } API BREAKING CHANGES @@ -439,7 +400,98 @@ CODE - likewise io.MousePos and GetMousePos() will use OS coordinates. If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos. + - 2025/06/25 (1.92.0) - layout: commented out legacy ErrorCheckUsingSetCursorPosToExtendParentBoundaries() fallback obsoleted in 1.89 (August 2022) which allowed a SetCursorPos()/SetCursorScreenPos() call WITHOUT AN ITEM + to extend parent window/cell boundaries. Replaced with assert/tooltip that would already happens if previously using IMGUI_DISABLE_OBSOLETE_FUNCTIONS. (#5548, #4510, #3355, #1760, #1490, #4152, #150) + - Incorrect way to make a window content size 200x200: + Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); + - Correct ways to make a window content size 200x200: + Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); + Begin(...) + Dummy(ImVec2(200,200)) + End(); + - TL;DR; if the assert triggers, you can add a Dummy({0,0}) call to validate extending parent boundaries. +>- 2025/06/11 (1.92.0) - Renamed/moved ImGuiConfigFlags_DpiEnableScaleFonts -> bool io.ConfigDpiScaleFonts. + - Renamed/moved ImGuiConfigFlags_DpiEnableScaleViewports -> bool io.ConfigDpiScaleViewports. **Neither of those flags are very useful in current code. They will be useful once we merge font changes.** + - 2025/06/11 (1.92.0) - THIS VERSION CONTAINS THE LARGEST AMOUNT OF BREAKING CHANGES SINCE 2015! I TRIED REALLY HARD TO KEEP THEM TO A MINIMUM, REDUCE THE AMOUNT OF INTERFERENCES, BUT INEVITABLY SOME USERS WILL BE AFFECTED. + IN ORDER TO HELP US IMPROVE THE TRANSITION PROCESS, INCL. DOCUMENTATION AND COMMENTS, PLEASE REPORT **ANY** DOUBT, CONFUSION, QUESTIONS, FEEDBACK TO: https://github.com/ocornut/imgui/issues/ + As part of the plan to reduce impact of API breaking changes, several unfinished changes/features/refactors related to font and text systems and scaling will be part of subsequent releases (1.92.1+). + If you are updating from an old version, and expecting a massive or difficult update, consider first updating to 1.91.9 to reduce the amount of changes. + - Hard to read? Refer to 'docs/Changelog.txt' for a less compact and more complete version of this! + - Fonts: **IMPORTANT**: if your app was solving the OSX/iOS Retina screen specific logical vs display scale problem by setting io.DisplayFramebufferScale (e.g. to 2.0f) + setting io.FontGlobalScale (e.g. to 1.0f/2.0f) + loading fonts at scaled sizes (e.g. size X * 2.0f): + This WILL NOT map correctly to the new system! Because font will rasterize as requested size. + - With a legacy backend (< 1.92): Instead of setting io.FontGlobalScale = 1.0f/N -> set ImFontCfg::RasterizerDensity = N. This already worked before, but is now pretty much required. + - With a new backend (1.92+): This should be all automatic. FramebufferScale is automatically used to set current font RasterizerDensity. FramebufferScale is a per-viewport property provided by backend through the Platform_GetWindowFramebufferScale() handler in 'docking' branch. + - Fonts: **IMPORTANT** on Font Sizing: Before 1.92, fonts were of a single size. They can now be dynamically sized. + - PushFont() API now has a REQUIRED size parameter. + - Before 1.92: PushFont() always used font "default" size specified in AddFont() call. It is equivalent to calling PushFont(font, font->LegacySize). + - Since 1.92: PushFont(font, 0.0f) preserve the current font size which is a shared value. + - To use old behavior: use 'ImGui::PushFont(font, font->LegacySize)' at call site. + - Kept inline single parameter function. Will obsolete. + - Fonts: **IMPORTANT** on Font Merging: + - When searching for a glyph in multiple merged fonts: we search for the FIRST font source which contains the desired glyph. + Because the user doesn't need to provide glyph ranges any more, it is possible that a glyph that you expected to fetch from a secondary/merged icon font may be erroneously fetched from the primary font. + - When searching for a glyph in multiple merged fonts: we now search for the FIRST font source which contains the desired glyph. This is technically a different behavior than before! + - e.g. If you are merging fonts you may have glyphs that you expected to load from Font Source 2 which exists in Font Source 1. + After the update and when using a new backend, those glyphs may now loaded from Font Source 1! + - We added `ImFontConfig::GlyphExcludeRanges[]` to specify ranges to exclude from a given font source: + // Add Font Source 1 but ignore ICON_MIN_FA..ICON_MAX_FA range + static ImWchar exclude_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; + ImFontConfig cfg1; + cfg1.GlyphExcludeRanges = exclude_ranges; + io.Fonts->AddFontFromFileTTF("segoeui.ttf", 0.0f, &cfg1); + // Add Font Source 2, which expects to use the range above + ImFontConfig cfg2; + cfg2.MergeMode = true; + io.Fonts->AddFontFromFileTTF("FontAwesome4.ttf", 0.0f, &cfg2); + - You can use `Metrics/Debugger->Fonts->Font->Input Glyphs Overlap Detection Tool` to see list of glyphs available in multiple font sources. This can facilitate unde + - Fonts: ImFont::FontSize was removed and does not make sense anymore. ImFont::LegacySize is the size passed to AddFont(). + - Fonts: Removed support for PushFont(NULL) which was a shortcut for "default font". + - Fonts: Renamed/moved 'io.FontGlobalScale' to 'style.FontScaleMain'. + - Textures: all API functions taking a 'ImTextureID' parameter are now taking a 'ImTextureRef'. Affected functions are: ImGui::Image(), ImGui::ImageWithBg(), ImGui::ImageButton(), ImDrawList::AddImage(), ImDrawList::AddImageQuad(), ImDrawList::AddImageRounded(). + - Fonts: obsoleted ImFontAtlas::GetTexDataAsRGBA32(), GetTexDataAsAlpha8(), Build(), SetTexID(), IsBuilt() functions. The new protocol for backends to handle textures doesn't need them. Kept redirection functions (will obsolete). + - Fonts: ImFontConfig::OversampleH/OversampleV default to automatic (== 0) since v1.91.8. It is quite important you keep it automatic until we decide if we want to provide a way to express finer policy, otherwise you will likely waste texture space when using large glyphs. Note that the imgui_freetype backend doesn't use and does not need oversampling. + - Fonts: specifying glyph ranges is now unnecessary. The value of ImFontConfig::GlyphRanges[] is only useful for legacy backends. All GetGlyphRangesXXXX() functions are now marked obsolete: GetGlyphRangesDefault(), GetGlyphRangesGreek(), GetGlyphRangesKorean(), GetGlyphRangesJapanese(), GetGlyphRangesChineseSimplifiedCommon(), GetGlyphRangesChineseFull(), GetGlyphRangesCyrillic(), GetGlyphRangesThai(), GetGlyphRangesVietnamese(). + - Fonts: removed ImFontAtlas::TexDesiredWidth to enforce a texture width. (#327) + - Fonts: if you create and manage ImFontAtlas instances yourself (instead of relying on ImGuiContext to create one, you'll need to call ImFontAtlasUpdateNewFrame() yourself. An assert will trigger if you don't. + - Fonts: obsolete ImGui::SetWindowFontScale() which is not useful anymore. Prefer using 'PushFont(NULL, style.FontSizeBase * factor)' or to manipulate other scaling factors. + - Fonts: obsoleted ImFont::Scale which is not useful anymore. + - Fonts: generally reworked Internals of ImFontAtlas and ImFont. While in theory a vast majority of users shouldn't be affected, some use cases or extensions might be. Among other things: + - ImDrawCmd::TextureId has been changed to ImDrawCmd::TexRef. + - ImFontAtlas::TexID has been changed to ImFontAtlas::TexRef. + - ImFontAtlas::ConfigData[] has been renamed to ImFontAtlas::Sources[] + - ImFont::ConfigData[], ConfigDataCount has been renamed to Sources[], SourceCount. + - Each ImFont has a number of ImFontBaked instances corresponding to actively used sizes. ImFont::GetFontBaked(size) retrieves the one for a given size. + - Fields moved from ImFont to ImFontBaked: IndexAdvanceX[], Glyphs[], Ascent, Descent, FindGlyph(), FindGlyphNoFallback(), GetCharAdvance(). + - Fields moved from ImFontAtlas to ImFontAtlas->Tex: ImFontAtlas::TexWidth => TexData->Width, ImFontAtlas::TexHeight => TexData->Height, ImFontAtlas::TexPixelsAlpha8/TexPixelsRGBA32 => TexData->GetPixels(). + - Widget code may use ImGui::GetFontBaked() instead of ImGui::GetFont() to access font data for current font at current font size (and you may use font->GetFontBaked(size) to access it for any other size.) + - Fonts: (users of imgui_freetype): renamed ImFontAtlas::FontBuilderFlags to ImFontAtlas::FontLoaderFlags. Renamed ImFontConfig::FontBuilderFlags to ImFontConfig::FontLoaderFlags. Renamed ImGuiFreeTypeBuilderFlags to ImGuiFreeTypeLoaderFlags. + If you used runtime imgui_freetype selection rather than the default IMGUI_ENABLE_FREETYPE compile-time option: Renamed/reworked ImFontBuilderIO into ImFontLoader. Renamed ImGuiFreeType::GetBuilderForFreeType() to ImGuiFreeType::GetFontLoader(). + - old: io.Fonts->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType() + - new: io.Fonts->FontLoader = ImGuiFreeType::GetFontLoader() + - new: io.Fonts->SetFontLoader(ImGuiFreeType::GetFontLoader()) to change dynamically at runtime [from 1.92.1] + - Fonts: (users of custom rectangles, see #8466): Renamed AddCustomRectRegular() to AddCustomRect(). Added GetCustomRect() as a replacement for GetCustomRectByIndex() + CalcCustomRectUV(). + - The output type of GetCustomRect() is now ImFontAtlasRect, which include UV coordinates. X->x, Y->y, Width->w, Height->h. + - old: + const ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(custom_rect_id); + ImVec2 uv0, uv1; + atlas->GetCustomRectUV(r, &uv0, &uv1); + ImGui::Image(atlas->TexRef, ImVec2(r->w, r->h), uv0, uv1); + - new; + ImFontAtlasRect r; + atlas->GetCustomRect(custom_rect_id, &r); + ImGui::Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1); + - We added a redirecting typedef but haven't attempted to magically redirect the field names, as this API is rarely used and the fix is simple. + - Obsoleted AddCustomRectFontGlyph() as the API does not make sense for scalable fonts. Kept existing function which uses the font "default size" (Sources[0]->LegacySize). Added a helper AddCustomRectFontGlyphForSize() which is immediately marked obsolete, but can facilitate transitioning old code. + - Prefer adding a font source (ImFontConfig) using a custom/procedural loader. + - DrawList: Renamed ImDrawList::PushTextureID()/PopTextureID() to PushTexture()/PopTexture(). + - Backends: removed ImGui_ImplXXXX_CreateFontsTexture()/ImGui_ImplXXXX_DestroyFontsTexture() for all backends that had them. They should not be necessary any more. + - 2025/05/23 (1.92.0) - Fonts: changed ImFont::CalcWordWrapPositionA() to ImFont::CalcWordWrapPosition() + - old: const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, ....); + - new: const char* ImFont::CalcWordWrapPosition (float size, const char* text, ....); + The leading 'float scale' parameters was changed to 'float size'. This was necessary as 'scale' is assuming standard font size which is a concept we aim to eliminate in an upcoming update. Kept inline redirection function. + - 2025/05/15 (1.92.0) - TreeNode: renamed ImGuiTreeNodeFlags_NavLeftJumpsBackHere to ImGuiTreeNodeFlags_NavLeftJumpsToParent for clarity. Kept inline redirection enum (will obsolete). + - 2025/05/15 (1.92.0) - Commented out PushAllowKeyboardFocus()/PopAllowKeyboardFocus() which was obsoleted in 1.89.4. Use PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop)/PopItemFlag() instead. (#3092) + - 2025/05/15 (1.92.0) - Commented out ImGuiListClipper::ForceDisplayRangeByIndices() which was obsoleted in 1.89.6. Use ImGuiListClipper::IncludeItemsByIndex() instead. - 2025/03/05 (1.91.9) - BeginMenu(): Internals: reworked mangling of menu windows to use "###Menu_00" etc. instead of "##Menu_00", allowing them to also store the menu name before it. This shouldn't affect code unless directly accessing menu window from their mangled name. + - 2025/04/16 (1.91.9) - Internals: RenderTextEllipsis() function removed the 'float clip_max_x' parameter directly preceding 'float ellipsis_max_x'. Values were identical for a vast majority of users. (#8387) - 2025/02/27 (1.91.9) - Image(): removed 'tint_col' and 'border_col' parameter from Image() function. Added ImageWithBg() replacement. (#8131, #8238) - old: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1), ImVec4 tint_col = (1,1,1,1), ImVec4 border_col = (0,0,0,0)); - new: void Image (ImTextureID tex_id, ImVec2 image_size, ImVec2 uv0 = (0,0), ImVec2 uv1 = (1,1)); @@ -485,7 +537,7 @@ CODE - 2024/10/03 (1.91.3) - drags: treat v_min==v_max as a valid clamping range when != 0.0f. Zero is a still special value due to legacy reasons, unless using ImGuiSliderFlags_ClampZeroRange. (#7968, #3361, #76) - drags: extended behavior of ImGuiSliderFlags_AlwaysClamp to include _ClampZeroRange. It considers v_min==v_max==0.0f as a valid clamping range (aka edits not allowed). although unlikely, it you wish to only clamp on text input but want v_min==v_max==0.0f to mean unclamped drags, you can use _ClampOnInput instead of _AlwaysClamp. (#7968, #3361, #76) - - 2024/09/10 (1.91.2) - internals: using multiple overlayed ButtonBehavior() with same ID will now have io.ConfigDebugHighlightIdConflicts=true feature emit a warning. (#8030) + - 2024/09/10 (1.91.2) - internals: using multiple overlaid ButtonBehavior() with same ID will now have io.ConfigDebugHighlightIdConflicts=true feature emit a warning. (#8030) it was one of the rare case where using same ID is legal. workarounds: (1) use single ButtonBehavior() call with multiple _MouseButton flags, or (2) surround the calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag() - 2024/08/23 (1.91.1) - renamed ImGuiChildFlags_Border to ImGuiChildFlags_Borders for consistency. kept inline redirection flag. - 2024/08/22 (1.91.1) - moved some functions from ImGuiIO to ImGuiPlatformIO structure: @@ -678,7 +730,7 @@ CODE - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(), ImGui::IsKeyDown(). Removed GetKeyIndex(), now unnecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details. - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX) - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX) - - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes). + - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to still function with legacy key codes). - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.* - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert. - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper. @@ -887,7 +939,7 @@ CODE - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete). - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete). - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency. - - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix. + - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicitly to fix. - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type. - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely. - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete). @@ -1189,6 +1241,9 @@ CODE #define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Hold CTRL to display for all candidates. CTRL+Arrow to change last direction. #define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window +// Default font size if unspecified in both style.FontSizeBase and AddFontXXX() calls. +static const float FONT_DEFAULT_SIZE = 20.0f; + // When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch. static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear @@ -1274,6 +1329,10 @@ static void UpdateMouseWheel(); static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt); // Misc +static void UpdateFontsNewFrame(); +static void UpdateFontsEndFrame(); +static void UpdateTexturesNewFrame(); +static void UpdateTexturesEndFrame(); static void UpdateSettings(); static int UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect); static void RenderWindowShadow(ImGuiWindow* window); @@ -1350,6 +1409,10 @@ static void* GImAllocatorUserData = NULL; ImGuiStyle::ImGuiStyle() { + FontSizeBase = 0.0f; // Will default to io.Fonts->Fonts[0] on first frame. + FontScaleMain = 1.0f; // Main scale factor. May be set by application once, or exposed to end-user. + FontScaleDpi = 1.0f; // Additional scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. + Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui. DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. WindowPadding = ImVec2(8,8); // Padding within a window @@ -1386,6 +1449,9 @@ ImGuiStyle::ImGuiStyle() TabBarOverlineSize = 1.0f; // Thickness of tab-bar overline, which highlights the selected tab-bar. TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees). TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell + TreeLinesFlags = ImGuiTreeNodeFlags_DrawLinesNone; + TreeLinesSize = 1.0f; // Thickness of outlines when using ImGuiTreeNodeFlags_DrawLines. + TreeLinesRounding = 0.0f; // Radius of lines connecting child nodes to the vertical line. ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. @@ -1412,14 +1478,20 @@ ImGuiStyle::ImGuiStyle() HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse. HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad. + // [Internal] + _MainScale = 1.0f; + _NextFrameFontSizeBase = 0.0f; + // Default theme ImGui::StyleColorsDark(this); } -// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you. + +// Scale all spacing/padding/thickness values. Do not scale fonts. // Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times. void ImGuiStyle::ScaleAllSizes(float scale_factor) { + _MainScale *= scale_factor; WindowPadding = ImTrunc(WindowPadding * scale_factor); WindowRounding = ImTrunc(WindowRounding * scale_factor); WindowMinSize = ImTrunc(WindowMinSize * scale_factor); @@ -1444,6 +1516,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) TabCloseButtonMinWidthSelected = (TabCloseButtonMinWidthSelected > 0.0f && TabCloseButtonMinWidthSelected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthSelected * scale_factor) : TabCloseButtonMinWidthSelected; TabCloseButtonMinWidthUnselected = (TabCloseButtonMinWidthUnselected > 0.0f && TabCloseButtonMinWidthUnselected != FLT_MAX) ? ImTrunc(TabCloseButtonMinWidthUnselected * scale_factor) : TabCloseButtonMinWidthUnselected; TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor); + TreeLinesRounding = ImTrunc(TreeLinesRounding * scale_factor); SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor); DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor); DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor); @@ -1468,9 +1541,11 @@ ImGuiIO::ImGuiIO() UserData = NULL; Fonts = NULL; - FontGlobalScale = 1.0f; FontDefault = NULL; FontAllowUserScaling = false; +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + FontGlobalScale = 1.0f; // Use style.FontScaleMain instead! +#endif DisplayFramebufferScale = ImVec2(1.0f, 1.0f); // Keyboard/Gamepad Navigation options @@ -1791,7 +1866,7 @@ void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down) // On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button. if (ConfigMacOSXBehaviors && mouse_button == 0 && MouseCtrlLeftAsRightClick) { - // Order of both statements matterns: this event will still release mouse button 1 + // Order of both statements matters: this event will still release mouse button 1 mouse_button = 1; if (!down) MouseCtrlLeftAsRightClick = false; @@ -2058,6 +2133,12 @@ char* ImStrdup(const char* str) return (char*)memcpy(buf, (const void*)str, len + 1); } +void* ImMemdup(const void* src, size_t size) +{ + void* dst = IM_ALLOC(size); + return memcpy(dst, src, size); +} + char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src) { size_t dst_buf_size = p_dst_size ? *p_dst_size : ImStrlen(dst) + 1; @@ -3245,10 +3326,17 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) if (table) IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y); - clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart); - bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y); + bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision((float)clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y); if (affected_by_floating_point_precision) + { + // Mitigation/hack for very large range: assume last time height constitute line height. clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries. + window->DC.CursorPos.y = (float)(clipper->StartPosY + clipper->ItemsHeight); + } + else + { + clipper->ItemsHeight = (float)(window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart); + } if (clipper->ItemsHeight == 0.0f && clipper->ItemsCount == INT_MAX) // Accept that no item have been submitted if in indeterminate mode. return false; IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!"); @@ -3272,7 +3360,10 @@ static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper) // Add range selected to be included for navigation const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav); if (is_nav_request) + { + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringRect.Min.y, g.NavScoringRect.Max.y, 0, 0)); data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0)); + } if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1) data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount)); @@ -3484,6 +3575,8 @@ static const ImGuiStyleVarInfo GStyleVarsInfo[] = { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) }, // ImGuiStyleVar_TabBarOverlineSize { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)}, // ImGuiStyleVar_TableAngledHeadersAngle { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TreeLinesSize)}, // ImGuiStyleVar_TreeLinesSize + { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, TreeLinesRounding)}, // ImGuiStyleVar_TreeLinesRounding { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign { 2, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign { 1, ImGuiDataType_Float, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize @@ -3614,6 +3707,7 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) case ImGuiCol_ResizeGrip: return "ResizeGrip"; case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered"; case ImGuiCol_ResizeGripActive: return "ResizeGripActive"; + case ImGuiCol_InputTextCursor: return "InputTextCursor"; case ImGuiCol_TabHovered: return "TabHovered"; case ImGuiCol_Tab: return "Tab"; case ImGuiCol_TabSelected: return "TabSelected"; @@ -3634,6 +3728,7 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt"; case ImGuiCol_TextLink: return "TextLink"; case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; + case ImGuiCol_TreeLines: return "TreeLines"; case ImGuiCol_DragDropTarget: return "DragDropTarget"; case ImGuiCol_NavCursor: return "NavCursor"; case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight"; @@ -3709,7 +3804,7 @@ void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end // Default clip_rect uses (pos_min,pos_max) // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges) -// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList. +// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especially for text above draw_list->DrawList. // Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take // better advantage of the render function taking size into account for coarse clipping. void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) @@ -3756,18 +3851,19 @@ void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, cons } // Another overly complex function until we reorganize everything into a nice all-in-one helper. -// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display. +// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) from 'ellipsis_max_x' which may be beyond it. // This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move. -void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known) +// (BREAKING) On 2025/04/16 we removed the 'float clip_max_x' parameters which was preceeding 'float ellipsis_max' and was the same value for 99% of users. +void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known) { ImGuiContext& g = *GImGui; if (text_end_full == NULL) text_end_full = FindRenderedTextEnd(text); const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f); - //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255)); - //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255)); - //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255)); + //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 6), IM_COL32(0, 0, 255, 255)); + //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y - 2), ImVec2(ellipsis_max_x, pos_max.y + 3), IM_COL32(0, 255, 0, 255)); + // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels. if (text_size.x > pos_max.x - pos_min.x) { @@ -3780,17 +3876,12 @@ void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, con const float font_size = draw_list->_Data->FontSize; const float font_scale = draw_list->_Data->FontScale; const char* text_end_ellipsis = NULL; - const float ellipsis_width = font->EllipsisWidth * font_scale; + ImFontBaked* baked = font->GetFontBaked(font_size); + const float ellipsis_width = baked->GetCharAdvance(font->EllipsisChar) * font_scale; // We can now claim the space between pos_max.x and ellipsis_max.x const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f); float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x; - if (text == text_end_ellipsis && text_end_ellipsis < text_end_full) - { - // Always display at least 1 character if there's no room for character + ellipsis - text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full); - text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x; - } while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1])) { // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text) @@ -3799,15 +3890,14 @@ void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, con } // Render text, render ellipsis - RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f)); + RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f)); + ImVec4 cpu_fine_clip_rect(pos_min.x, pos_min.y, pos_max.x, pos_max.y); ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y)); - if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x) - for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale) - font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar); + font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar, &cpu_fine_clip_rect); } else { - RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f)); + RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_end_full, &text_size, ImVec2(0.0f, 0.0f)); } if (g.LogEnabled) @@ -3879,7 +3969,7 @@ void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCurso ImGuiContext& g = *GImGui; if (mouse_cursor <= ImGuiMouseCursor_None || mouse_cursor >= ImGuiMouseCursor_COUNT) // We intentionally accept out of bound values. mouse_cursor = ImGuiMouseCursor_Arrow; - ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas; + ImFontAtlas* font_atlas = g.DrawListSharedData.FontAtlas; for (ImGuiViewportP* viewport : g.Viewports) { // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor. @@ -3891,12 +3981,12 @@ void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCurso if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale))) continue; ImDrawList* draw_list = GetForegroundDrawList(viewport); - ImTextureID tex_id = font_atlas->TexID; - draw_list->PushTextureID(tex_id); - draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow); - draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow); - draw_list->AddImage(tex_id, pos, pos + size * scale, uv[2], uv[3], col_border); - draw_list->AddImage(tex_id, pos, pos + size * scale, uv[0], uv[1], col_fill); + ImTextureRef tex_ref = font_atlas->TexRef; + draw_list->PushTexture(tex_ref); + draw_list->AddImage(tex_ref, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow); + draw_list->AddImage(tex_ref, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow); + draw_list->AddImage(tex_ref, pos, pos + size * scale, uv[2], uv[3], col_border); + draw_list->AddImage(tex_ref, pos, pos + size * scale, uv[0], uv[1], col_fill); if (mouse_cursor == ImGuiMouseCursor_Wait || mouse_cursor == ImGuiMouseCursor_Progress) { float a_min = ImFmod((float)g.Time * 5.0f, 2.0f * IM_PI); @@ -3904,7 +3994,7 @@ void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCurso draw_list->PathArcTo(pos + ImVec2(14, -1) * scale, 6.0f * scale, a_min, a_max); draw_list->PathStroke(col_fill, ImDrawFlags_None, 3.0f * scale); } - draw_list->PopTextureID(); + draw_list->PopTexture(); } } @@ -3990,10 +4080,14 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) Initialized = false; ConfigFlagsCurrFrame = ConfigFlagsLastFrame = ImGuiConfigFlags_None; - FontAtlasOwnedByContext = shared_font_atlas ? false : true; + Font = NULL; - FontSize = FontBaseSize = FontScale = CurrentDpiScale = 0.0f; + FontBaked = NULL; + FontSize = FontSizeBase = FontBakedScale = CurrentDpiScale = 0.0f; + FontRasterizerDensity = 1.0f; IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); + if (shared_font_atlas == NULL) + IO.Fonts->OwnerContext = this; Time = 0.0f; FrameCount = 0; FrameCountEnded = FrameCountPlatformEnded = FrameCountRendered = -1; @@ -4018,7 +4112,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) WheelingWindowStartFrame = WheelingWindowScrolledFrame = -1; WheelingWindowReleaseTimer = 0.0f; - DebugDrawIdConflicts = 0; + DebugDrawIdConflictsId = 0; DebugHookIdInfo = 0; HoveredId = HoveredIdPreviousFrame = 0; HoveredIdPreviousFrameItemCount = 0; @@ -4098,9 +4192,11 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) // All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac... // FIXME: Because this value is stored, it annoyingly interfere with toggling io.ConfigMacOSXBehaviors updating this.. + ConfigNavWindowingWithGamepad = true; ConfigNavWindowingKeyNext = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiKey_Tab); ConfigNavWindowingKeyPrev = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab); NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL; + NavWindowingInputSource = ImGuiInputSource_None; NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f; NavWindowingToggleLayer = false; NavWindowingToggleKey = ImGuiKey_None; @@ -4133,6 +4229,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) MouseCursor = ImGuiMouseCursor_Arrow; MouseStationaryTimer = 0.0f; + InputTextPasswordFontBackupFlags = ImFontFlags_None; TempInputId = 0; memset(&DataTypeZeroValue, 0, sizeof(DataTypeZeroValue)); BeginMenuDepth = BeginComboDepth = 0; @@ -4156,7 +4253,6 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) PlatformImeData.InputPos = ImVec2(0.0f, 0.0f); PlatformImeDataPrev.InputPos = ImVec2(-1.0f, -1.0f); // Different to ensure initial submission - PlatformImeViewport = 0; DockNodeWindowMenuHandler = NULL; @@ -4263,6 +4359,18 @@ void ImGui::Initialize() DockContextInitialize(&g); #endif + // Print a debug message when running with debug feature IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS because it is very slow. + // DO NOT COMMENT OUT THIS MESSAGE. IT IS DESIGNED TO REMIND YOU THAT IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS SHOULD ONLY BE TEMPORARILY ENABLED. +#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS + DebugLog("IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS is enabled.\nMust disable after use! Otherwise Dear ImGui will run slower.\n"); +#endif + + // ImDrawList/ImFontAtlas are designed to function without ImGui, and 99% of it works without an ImGui context. + // But this link allows us to facilitate/handle a few edge cases better. + ImFontAtlas* atlas = g.IO.Fonts; + g.DrawListSharedData.Context = &g; + RegisterFontAtlas(atlas); + g.Initialized = true; } @@ -4274,12 +4382,15 @@ void ImGui::Shutdown() IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?"); // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame) - if (g.IO.Fonts && g.FontAtlasOwnedByContext) + for (ImFontAtlas* atlas : g.FontAtlases) { - g.IO.Fonts->Locked = false; - IM_DELETE(g.IO.Fonts); + UnregisterFontAtlas(atlas); + if (atlas->OwnerContext == &g) + { + atlas->Locked = false; + IM_DELETE(atlas); + } } - g.IO.Fonts = NULL; g.DrawListSharedData.TempBuffer.clear(); // Cleanup of other data are conditional on actually having initialized Dear ImGui. @@ -4415,12 +4526,12 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NUL LastFrameJustFocused = -1; LastTimeActive = -1.0f; FontRefSize = 0.0f; - FontWindowScale = FontWindowScaleParents = FontDpiScale = 1.0f; + FontWindowScale = FontWindowScaleParents = 1.0f; SettingsOffset = -1; DockOrder = -1; DrawList = &DrawListInst; DrawList->_OwnerName = Name; - DrawList->_Data = &Ctx->DrawListSharedData; + DrawList->_SetDrawListSharedData(&Ctx->DrawListSharedData); NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX); IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass(); } @@ -4440,8 +4551,15 @@ static void SetCurrentWindow(ImGuiWindow* window) g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL; if (window) { - g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); - g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize; + bool backup_skip_items = window->SkipItems; + window->SkipItems = false; + if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) + { + ImGuiViewport* viewport = window->Viewport; + g.FontRasterizerDensity = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale.x : g.IO.DisplayFramebufferScale.x; // == SetFontRasterizerDensity() + } + ImGui::UpdateCurrentFontSize(0.0f); + window->SkipItems = backup_skip_items; ImGui::NavUpdateCurrentWindowIsScrollPushableX(); } } @@ -4454,6 +4572,8 @@ void ImGui::GcCompactTransientMiscBuffers() g.MultiSelectTempDataStacked = 0; g.MultiSelectTempData.clear_destruct(); TableGcCompactSettings(); + for (ImFontAtlas* atlas : g.FontAtlases) + atlas->CompactCache(); } // Free up/compact internal window buffers, we can use this when a window becomes unused. @@ -4730,7 +4850,8 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) return true; } -// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered(). +// Internal facing ItemHoverable() used when submitting widgets. THIS IS A SUBMISSION NOT A HOVER CHECK. +// Returns whether the item was hovered, logic differs slightly from IsItemHovered(). // (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call) // FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28. // If you used this in your legacy/custom widgets code: @@ -4742,11 +4863,12 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flag ImGuiWindow* window = g.CurrentWindow; // Detect ID conflicts + // (this is specifically done here by comparing on hover because it allows us a detection of duplicates that is algorithmically extra cheap, 1 u32 compare per item. No O(log N) lookup whatsoever) #ifndef IMGUI_DISABLE_DEBUG_TOOLS if (id != 0 && g.HoveredIdPreviousFrame == id && (item_flags & ImGuiItemFlags_AllowDuplicateId) == 0) { g.HoveredIdPreviousFrameItemCount++; - if (g.DebugDrawIdConflicts == id) + if (g.DebugDrawIdConflictsId == id) window->DrawList->AddRect(bb.Min - ImVec2(1,1), bb.Max + ImVec2(1,1), IM_COL32(255, 0, 0, 255), 0.0f, ImDrawFlags_None, 2.0f); } #endif @@ -5015,7 +5137,7 @@ static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t draw if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount) { draw_list->_ResetForNewFrame(); - draw_list->PushTextureID(g.IO.Fonts->TexID); + draw_list->PushTexture(g.IO.Fonts->TexRef); draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false); viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount; } @@ -5240,7 +5362,7 @@ static bool IsWindowActiveAndVisible(ImGuiWindow* window) } // The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app) -void ImGui::UpdateHoveredWindowAndCaptureFlags() +void ImGui::UpdateHoveredWindowAndCaptureFlags(const ImVec2& mouse_pos) { ImGuiContext& g = *GImGui; ImGuiIO& io = g.IO; @@ -5254,7 +5376,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame. // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms. bool clear_hovered_windows = false; - FindHoveredWindowEx(g.IO.MousePos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow); + FindHoveredWindowEx(mouse_pos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow); IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport); g.HoveredWindowBeforeClear = g.HoveredWindow; @@ -5325,6 +5447,46 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false; } +static void ImGui::UpdateTexturesNewFrame() +{ + // Cannot update every atlases based on atlas's FrameCount < g.FrameCount, because an atlas may be shared by multiple contexts with different frame count. + ImGuiContext& g = *GImGui; + const bool has_textures = (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0; + for (ImFontAtlas* atlas : g.FontAtlases) + { + if (atlas->OwnerContext == &g) + { + ImFontAtlasUpdateNewFrame(atlas, g.FrameCount, has_textures); + } + else + { + // (1) If you manage font atlases yourself, e.g. create a ImFontAtlas yourself you need to call ImFontAtlasUpdateNewFrame() on it. + // Otherwise, calling ImGui::CreateContext() without parameter will create an atlas owned by the context. + // (2) If you have multiple font atlases, make sure the 'atlas->RendererHasTextures' as specified in the ImFontAtlasUpdateNewFrame() call matches for that. + // (3) If you have multiple imgui contexts, they also need to have a matching value for ImGuiBackendFlags_RendererHasTextures. + IM_ASSERT(atlas->Builder != NULL && atlas->Builder->FrameCount != -1); + IM_ASSERT(atlas->RendererHasTextures == has_textures); + } + } +} + +// Build a single texture list +static void ImGui::UpdateTexturesEndFrame() +{ + ImGuiContext& g = *GImGui; + g.PlatformIO.Textures.resize(0); + for (ImFontAtlas* atlas : g.FontAtlases) + for (ImTextureData* tex : atlas->TexList) + { + // We provide this information so backends can decide whether to destroy textures. + // This means in practice that if N imgui contexts are created with a shared atlas, we assume all of them have a backend initialized. + tex->RefCount = (unsigned short)atlas->RefCount; + g.PlatformIO.Textures.push_back(tex); + } + for (ImTextureData* tex : g.UserTextures) + g.PlatformIO.Textures.push_back(tex); +} + // Called once a frame. Followed by SetCurrentFont() which sets up the remaining data. // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal! static void SetupDrawListSharedData() @@ -5370,7 +5532,6 @@ void ImGui::NewFrame() UpdateSettings(); g.Time += g.IO.DeltaTime; - g.WithinFrameScope = true; g.FrameCount += 1; g.TooltipOverrideCount = 0; g.WindowsActiveCount = 0; @@ -5390,12 +5551,14 @@ void ImGui::NewFrame() // Update viewports (after processing input queue, so io.MouseHoveredViewport is set) UpdateViewportsNewFrame(); + // Update texture list (collect destroyed textures, etc.) + UpdateTexturesNewFrame(); + // Setup current font and draw list shared data - // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal! - g.IO.Fonts->Locked = true; SetupDrawListSharedData(); - SetCurrentFont(GetDefaultFont()); - IM_ASSERT(g.Font->IsLoaded()); + UpdateFontsNewFrame(); + + g.WithinFrameScope = true; // Mark rendering data as invalid to prevent user who may have a handle on it to use it. for (ImGuiViewportP* viewport : g.Viewports) @@ -5410,9 +5573,9 @@ void ImGui::NewFrame() // [DEBUG] if (!g.IO.ConfigDebugHighlightIdConflicts || !g.IO.KeyCtrl) // Count is locked while holding CTRL - g.DebugDrawIdConflicts = 0; + g.DebugDrawIdConflictsId = 0; if (g.IO.ConfigDebugHighlightIdConflicts && g.HoveredIdPreviousFrameItemCount > 1) - g.DebugDrawIdConflicts = g.HoveredIdPreviousFrame; + g.DebugDrawIdConflictsId = g.HoveredIdPreviousFrame; // Update HoveredId data if (!g.HoveredIdPreviousFrame) @@ -5536,7 +5699,7 @@ void ImGui::NewFrame() // Find hovered window // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame) // (currently needs to be done after the WasActive=Active loop and FindHoveredWindowEx uses ->Active) - UpdateHoveredWindowAndCaptureFlags(); + UpdateHoveredWindowAndCaptureFlags(g.IO.MousePos); // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering) UpdateMouseMovingWindowNewFrame(); @@ -5552,7 +5715,7 @@ void ImGui::NewFrame() // Platform IME data: reset for the frame g.PlatformImeDataPrev = g.PlatformImeData; - g.PlatformImeData.WantVisible = false; + g.PlatformImeData.WantVisible = g.PlatformImeData.WantTextInput = false; // Mouse wheel scrolling, scale UpdateMouseWheel(); @@ -5720,8 +5883,9 @@ static void InitViewportDrawData(ImGuiViewportP* viewport) draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0; draw_data->DisplayPos = viewport->Pos; draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size; - draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis? + draw_data->FramebufferScale = (viewport->FramebufferScale.x != 0.0f) ? viewport->FramebufferScale : io.DisplayFramebufferScale; draw_data->OwnerViewport = viewport; + draw_data->Textures = &ImGui::GetPlatformIO().Textures; } // Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering. @@ -5730,7 +5894,7 @@ static void InitViewportDrawData(ImGuiViewportP* viewport) // - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect(): // some frequently called functions which to modify both channels and clipping simultaneously tend to use the // more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds. -// - This is analoguous to PushFont()/PopFont() in the sense that are a mixing a global stack and a window stack, +// - This is analogous to PushFont()/PopFont() in the sense that are a mixing a global stack and a window stack, // which in the case of ClipRect is not so problematic but tends to be more restrictive for fonts. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { @@ -5852,7 +6016,7 @@ static void ImGui::RenderDimmedBackgrounds() if (window->DrawList->CmdBuffer.Size == 0) window->DrawList->AddDrawCmd(); window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size); - window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f); + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f); // FIXME-DPI window->DrawList->PopClipRect(); } @@ -5878,7 +6042,11 @@ void ImGui::EndFrame() // Don't process EndFrame() multiple times. if (g.FrameCountEnded == g.FrameCount) return; - IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?"); + if (!g.WithinFrameScope) + { + IM_ASSERT_USER_ERROR(g.WithinFrameScope, "Forgot to call ImGui::NewFrame()?"); + return; + } CallContextHooks(&g, ImGuiContextHookType_EndFramePre); @@ -5892,12 +6060,13 @@ void ImGui::EndFrame() ImGuiPlatformImeData* ime_data = &g.PlatformImeData; if (g.PlatformIO.Platform_SetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0) { - ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport); + ImGuiViewport* viewport = FindViewportByID(ime_data->ViewportId); IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y); if (viewport == NULL) viewport = GetMainViewport(); g.PlatformIO.Platform_SetImeDataFn(&g, viewport, ime_data); } + g.WantTextInputNextFrame = ime_data->WantTextInput ? 1 : 0; // Hide implicit/fallback "Debug" window if it hasn't been used g.WithinFrameScopeWithImplicitWindow = false; @@ -5937,6 +6106,7 @@ void ImGui::EndFrame() // End frame g.WithinFrameScope = false; g.FrameCountEnded = g.FrameCount; + UpdateFontsEndFrame(); // Initiate moving window + handle left-click and right-click focus UpdateMouseMovingWindowEndFrame(); @@ -5960,8 +6130,11 @@ void ImGui::EndFrame() g.Windows.swap(g.WindowsTempSortBuffer); g.IO.MetricsActiveWindows = g.WindowsActiveCount; + UpdateTexturesEndFrame(); + // Unlock font atlas - g.IO.Fonts->Locked = false; + for (ImFontAtlas* atlas : g.FontAtlases) + atlas->Locked = false; // Clear Input data for next frame g.IO.MousePosPrev = g.IO.MousePos; @@ -5973,7 +6146,7 @@ void ImGui::EndFrame() } // Prepare the data for rendering so you can call GetDrawData() -// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all: +// (As with anything within the ImGui:: namespace this doesn't touch your GPU or graphics API at all: // it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend) void ImGui::Render() { @@ -6038,6 +6211,12 @@ void ImGui::Render() g.IO.MetricsRenderIndices += draw_data->TotalIdxCount; } +#ifndef IMGUI_DISABLE_DEBUG_TOOLS + if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) + for (ImFontAtlas* atlas : g.FontAtlases) + ImFontAtlasDebugLogTextureRequests(atlas); +#endif + CallContextHooks(&g, ImGuiContextHookType_RenderPost); } @@ -6670,10 +6849,10 @@ static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_cur return; } - content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x); - content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y); - content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x); - content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y); + content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x); + content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y); + content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : ImTrunc64(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x); + content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : ImTrunc64(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y); } static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents) @@ -6684,35 +6863,35 @@ static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_cont const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y; ImVec2 size_pad = window->WindowPadding * 2.0f; ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars); + + // Determine maximum window size + // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction + ImVec2 size_max = ImVec2(FLT_MAX, FLT_MAX); + if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || (window->Flags & ImGuiWindowFlags_Popup) != 0) + { + if (!window->ViewportOwned) + size_max = ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f; + const int monitor_idx = window->ViewportAllowPlatformMonitorExtend; + if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size) + size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f; + } + if (window->Flags & ImGuiWindowFlags_Tooltip) { - // Tooltip always resize - return size_desired; + // Tooltip always resize (up to maximum size) + return ImMin(size_desired, size_max); } else { - // Maximum window size is determined by the viewport size or monitor size ImVec2 size_min = CalcWindowMinSize(window); - ImVec2 size_max = ImVec2(FLT_MAX, FLT_MAX); - - // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction - if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || (window->Flags & ImGuiWindowFlags_Popup) != 0) - { - if (!window->ViewportOwned) - size_max = ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f; - const int monitor_idx = window->ViewportAllowPlatformMonitorExtend; - if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size) - size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f; - } - - ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, size_max)); + ImVec2 size_auto_fit = ImClamp(size_desired, ImMin(size_min, size_max), size_max); // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars, // we may need to compute/store three variants of size_auto_fit, for x/y/xy. // Here we implement a workaround for child windows only, but a full solution would apply to normal windows as well: - if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & ImGuiChildFlags_ResizeY)) + if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & (ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeY))) size_auto_fit.y = window->SizeFull.y; - else if (!(window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->ChildFlags & ImGuiChildFlags_ResizeY)) + else if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && !(window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_AutoResizeX))) size_auto_fit.x = window->SizeFull.x; // When the window cannot fit all contents (either because of constraints, either because screen is too small), @@ -6832,7 +7011,9 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si ImGuiContext& g = *GImGui; ImGuiWindowFlags flags = window->Flags; - if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) + if ((flags & ImGuiWindowFlags_NoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) + return false; + if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && (window->ChildFlags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0) return false; if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window. return false; @@ -7310,8 +7491,12 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl // Close button if (has_close_button) + { + g.CurrentItemFlags |= ImGuiItemFlags_NoFocus; if (CloseButton(window->GetID("#CLOSE"), close_button_pos)) *p_open = false; + g.CurrentItemFlags &= ~ImGuiItemFlags_NoFocus; + } window->DC.NavLayerCurrent = ImGuiNavLayer_Main; g.CurrentItemFlags = item_flags_backup; @@ -7712,7 +7897,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) WindowSelectViewport(window); SetCurrentViewport(window, window->Viewport); - window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f; SetCurrentWindow(window); flags = window->Flags; @@ -7857,7 +8041,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // FIXME-DPI //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong SetCurrentViewport(window, window->Viewport); - window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f; SetCurrentWindow(window); } @@ -8056,12 +8239,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->InnerClipRect.Max.y = ImFloor(window->InnerRect.Max.y - window->WindowBorderSize * 0.5f); window->InnerClipRect.ClipWithFull(host_rect); - // Default item width. Make it proportional to window size if window manually resizes - if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) - window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f); - else - window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f); - // SCROLLING // Lock down maximum scrolling @@ -8079,7 +8256,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Setup draw list and outer clipping rectangle IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0); - window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); + window->DrawList->PushTexture(g.Font->ContainerAtlas->TexRef); PushClipRect(host_rect.Min, host_rect.Max, false); // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71) @@ -8168,13 +8345,18 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.MenuBarAppending = false; window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user); window->DC.TreeDepth = 0; - window->DC.TreeHasStackDataDepthMask = 0x00; + window->DC.TreeHasStackDataDepthMask = window->DC.TreeRecordsClippedNodesY2Mask = 0x00; window->DC.ChildWindows.resize(0); window->DC.StateStorage = &window->StateStorage; window->DC.CurrentColumns = NULL; window->DC.LayoutType = ImGuiLayoutType_Vertical; window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical; + // Default item width. Make it proportional to window size if window manually resizes + if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) + window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f); + else + window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f); window->DC.ItemWidth = window->ItemWidthDefault; window->DC.TextWrapPos = -1.0f; // disabled window->DC.ItemWidthStack.resize(0); @@ -8433,58 +8615,6 @@ void ImGui::End() SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport); } -// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only. -void ImGui::SetCurrentFont(ImFont* font) -{ - ImGuiContext& g = *GImGui; - IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? - IM_ASSERT(font->Scale > 0.0f); - g.Font = font; - g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale); - g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; - g.FontScale = g.FontSize / g.Font->FontSize; - - ImFontAtlas* atlas = g.Font->ContainerAtlas; - g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; - g.DrawListSharedData.TexUvLines = atlas->TexUvLines; - g.DrawListSharedData.Font = g.Font; - g.DrawListSharedData.FontSize = g.FontSize; - g.DrawListSharedData.FontScale = g.FontScale; - g.DrawListSharedData.ShadowRectIds = &atlas->ShadowRectIds[0]; - g.DrawListSharedData.ShadowRectUvs = &atlas->ShadowRectUvs[0]; -} - -// Use ImDrawList::_SetTextureID(), making our shared g.FontStack[] authorative against window-local ImDrawList. -// - Whereas ImDrawList::PushTextureID()/PopTextureID() is not to be used across Begin() calls. -// - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did... -// - Some code paths never really fully worked with multiple atlas textures. -// - The right-ish solution may be to remove _SetTextureID() and make AddText/RenderText lazily call PushTextureID()/PopTextureID() -// the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem -// because we have a concrete need and a test bed for multiple atlas textures. -void ImGui::PushFont(ImFont* font) -{ - ImGuiContext& g = *GImGui; - if (font == NULL) - font = GetDefaultFont(); - g.FontStack.push_back(font); - SetCurrentFont(font); - g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID); -} - -void ImGui::PopFont() -{ - ImGuiContext& g = *GImGui; - if (g.FontStack.Size <= 0) - { - IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!"); - return; - } - g.FontStack.pop_back(); - ImFont* font = g.FontStack.Size == 0 ? GetDefaultFont() : g.FontStack.back(); - SetCurrentFont(font); - g.CurrentWindow->DrawList->_SetTextureID(font->ContainerAtlas->TexID); -} - void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled) { ImGuiContext& g = *GImGui; @@ -8828,8 +8958,10 @@ void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond co return; window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); - // Set - window->Collapsed = collapsed; + // Queue applying in Begin() + if (window->WantCollapseToggle) + window->Collapsed ^= 1; + window->WantCollapseToggle = (window->Collapsed != collapsed); } void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size) @@ -8988,6 +9120,14 @@ ImFont* ImGui::GetFont() return GImGui->Font; } +ImFontBaked* ImGui::GetFontBaked() +{ + return GImGui->FontBaked; +} + +// Get current font size (= height in pixels) of current font, with global scale factors applied. +// - Use style.FontSizeBase to get value before global scale factors. +// - recap: ImGui::GetFontSize() == style.FontSizeBase * (style.FontScaleMain * style.FontScaleDpi * other_scaling_factors) float ImGui::GetFontSize() { return GImGui->FontSize; @@ -8998,15 +9138,16 @@ ImVec2 ImGui::GetFontTexUvWhitePixel() return GImGui->DrawListSharedData.TexUvWhitePixel; } +// Prefer using PushFont(NULL, style.FontSizeBase * factor), or use style.FontScaleMain to scale all windows. +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS void ImGui::SetWindowFontScale(float scale) { IM_ASSERT(scale > 0.0f); - ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->FontWindowScale = scale; - g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); - g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize; + UpdateCurrentFontSize(0.0f); } +#endif void ImGui::PushFocusScope(ImGuiID id) { @@ -9160,6 +9301,226 @@ bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) return window->ClipRect.Overlaps(ImRect(rect_min, rect_max)); } +//----------------------------------------------------------------------------- +// [SECTION] FONTS +//----------------------------------------------------------------------------- +// Most of the relevant font logic is in imgui_draw.cpp. +// Those are high-level support functions. +//----------------------------------------------------------------------------- +// - UpdateFontsNewFrame() [Internal] +// - UpdateFontsEndFrame() [Internal] +// - GetDefaultFont() [Internal] +// - RegisterUserTexture() [Internal] +// - UnregisterUserTexture() [Internal] +// - RegisterFontAtlas() [Internal] +// - UnregisterFontAtlas() [Internal] +// - SetCurrentFont() [Internal] +// - UpdateCurrentFontSize() [Internal] +// - SetFontRasterizerDensity() [Internal] +// - PushFont() +// - PopFont() +//----------------------------------------------------------------------------- + +void ImGui::UpdateFontsNewFrame() +{ + ImGuiContext& g = *GImGui; + if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) + for (ImFontAtlas* atlas : g.FontAtlases) + atlas->Locked = true; + + if (g.Style._NextFrameFontSizeBase != 0.0f) + { + g.Style.FontSizeBase = g.Style._NextFrameFontSizeBase; + g.Style._NextFrameFontSizeBase = 0.0f; + } + + // Apply default font size the first time + ImFont* font = ImGui::GetDefaultFont(); + if (g.Style.FontSizeBase <= 0.0f) + g.Style.FontSizeBase = (font->LegacySize > 0.0f ? font->LegacySize : FONT_DEFAULT_SIZE); + + // Set initial font + g.Font = font; + g.FontSizeBase = g.Style.FontSizeBase; + g.FontSize = 0.0f; + ImFontStackData font_stack_data = { font, g.Style.FontSizeBase, g.Style.FontSizeBase }; // <--- Will restore FontSize + SetCurrentFont(font_stack_data.Font, font_stack_data.FontSizeBeforeScaling, 0.0f); // <--- but use 0.0f to enable scale + g.FontStack.push_back(font_stack_data); + IM_ASSERT(g.Font->IsLoaded()); +} + +void ImGui::UpdateFontsEndFrame() +{ + PopFont(); +} + +ImFont* ImGui::GetDefaultFont() +{ + ImGuiContext& g = *GImGui; + ImFontAtlas* atlas = g.IO.Fonts; + if (atlas->Builder == NULL || atlas->Fonts.Size == 0) + ImFontAtlasBuildMain(atlas); + return g.IO.FontDefault ? g.IO.FontDefault : atlas->Fonts[0]; +} + +void ImGui::RegisterUserTexture(ImTextureData* tex) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(tex->RefCount > 0); + g.UserTextures.push_back(tex); +} + +void ImGui::UnregisterUserTexture(ImTextureData* tex) +{ + ImGuiContext& g = *GImGui; + g.UserTextures.find_erase(tex); +} + +void ImGui::RegisterFontAtlas(ImFontAtlas* atlas) +{ + ImGuiContext& g = *GImGui; + if (g.FontAtlases.Size == 0) + IM_ASSERT(atlas == g.IO.Fonts); + atlas->RefCount++; + g.FontAtlases.push_back(atlas); + ImFontAtlasAddDrawListSharedData(atlas, &g.DrawListSharedData); +} + +void ImGui::UnregisterFontAtlas(ImFontAtlas* atlas) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(atlas->RefCount > 0); + ImFontAtlasRemoveDrawListSharedData(atlas, &g.DrawListSharedData); + g.FontAtlases.find_erase(atlas); + atlas->RefCount--; +} + +// Use ImDrawList::_SetTexture(), making our shared g.FontStack[] authoritative against window-local ImDrawList. +// - Whereas ImDrawList::PushTexture()/PopTexture() is not to be used across Begin() calls. +// - Note that we don't propagate current texture id when e.g. Begin()-ing into a new window, we never really did... +// - Some code paths never really fully worked with multiple atlas textures. +// - The right-ish solution may be to remove _SetTexture() and make AddText/RenderText lazily call PushTexture()/PopTexture() +// the same way AddImage() does, but then all other primitives would also need to? I don't think we should tackle this problem +// because we have a concrete need and a test bed for multiple atlas textures. +// FIXME-NEWATLAS-V2: perhaps we can now leverage ImFontAtlasUpdateDrawListsTextures() ? +void ImGui::SetCurrentFont(ImFont* font, float font_size_before_scaling, float font_size_after_scaling) +{ + ImGuiContext& g = *GImGui; + g.Font = font; + g.FontSizeBase = font_size_before_scaling; + UpdateCurrentFontSize(font_size_after_scaling); + + if (font != NULL) + { + IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + IM_ASSERT(font->Scale > 0.0f); +#endif + ImFontAtlas* atlas = font->ContainerAtlas; + g.DrawListSharedData.FontAtlas = atlas; + g.DrawListSharedData.Font = font; + ImFontAtlasUpdateDrawListsSharedData(atlas); + if (g.CurrentWindow != NULL) + g.CurrentWindow->DrawList->_SetTexture(atlas->TexRef); + } +} + +void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + g.Style.FontSizeBase = g.FontSizeBase; + + // Early out to avoid hidden window keeping bakes referenced and out of GC reach. + // However this would leave a pretty subtle and damning error surface area if g.FontBaked was mismatching, so for now we null it. + // FIXME: perhaps g.FontSize should be updated? + if (window != NULL && window->SkipItems) + if (g.CurrentTable == NULL || g.CurrentTable->CurrentColumn != -1) // See 8465#issuecomment-2951509561. Ideally the SkipItems=true in tables would be amended with extra data. + return; + + // Restoring is pretty much only used by PopFont() + float final_size = (restore_font_size_after_scaling > 0.0f) ? restore_font_size_after_scaling : 0.0f; + if (final_size == 0.0f) + { + final_size = g.FontSizeBase; + + // Global scale factors + final_size *= g.Style.FontScaleMain; // Main global scale factor + final_size *= g.Style.FontScaleDpi; // Per-monitor/viewport DPI scale factor, automatically updated when io.ConfigDpiScaleFonts is enabled. + + // Window scale (mostly obsolete now) + if (window != NULL) + final_size *= window->FontWindowScale; + + // Legacy scale factors +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + final_size *= g.IO.FontGlobalScale; // Use style.FontScaleMain instead! + if (g.Font != NULL) + final_size *= g.Font->Scale; // Was never really useful. +#endif + } + + // Round font size + // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet. + // - We may support it better later and remove this rounding. + final_size = GetRoundedFontSize(final_size); + final_size = ImClamp(final_size, 1.0f, IMGUI_FONT_SIZE_MAX); + if (g.Font != NULL && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures)) + g.Font->CurrentRasterizerDensity = g.FontRasterizerDensity; + g.FontSize = final_size; + g.FontBaked = (g.Font != NULL && window != NULL) ? g.Font->GetFontBaked(final_size) : NULL; + g.FontBakedScale = (g.Font != NULL && window != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f; + g.DrawListSharedData.FontSize = g.FontSize; + g.DrawListSharedData.FontScale = g.FontBakedScale; + if (g.Font) + { + ImFontAtlas* atlas = g.Font->ContainerAtlas; + g.DrawListSharedData.ShadowRectIds = &atlas->ShadowRectIds[0]; + g.DrawListSharedData.ShadowRectUvs = &atlas->ShadowRectUvs[0]; + } +} + +// Exposed in case user may want to override setting density. +// IMPORTANT: Begin()/End() is overriding density. Be considerate of this you change it. +void ImGui::SetFontRasterizerDensity(float rasterizer_density) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures); + if (g.FontRasterizerDensity == rasterizer_density) + return; + g.FontRasterizerDensity = rasterizer_density; + UpdateCurrentFontSize(0.0f); +} + +// If you want to scale an existing font size! Read comments in imgui.h! +void ImGui::PushFont(ImFont* font, float font_size_base) +{ + ImGuiContext& g = *GImGui; + if (font == NULL) // Before 1.92 (June 2025), PushFont(NULL) == PushFont(GetDefaultFont()) + font = g.Font; + IM_ASSERT(font != NULL); + IM_ASSERT(font_size_base >= 0.0f); + + g.FontStack.push_back({ g.Font, g.FontSizeBase, g.FontSize }); + if (font_size_base == 0.0f) + font_size_base = g.FontSizeBase; // Keep current font size + SetCurrentFont(font, font_size_base, 0.0f); +} + +void ImGui::PopFont() +{ + ImGuiContext& g = *GImGui; + if (g.FontStack.Size <= 0) + { + IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!"); + return; + } + ImFontStackData* font_stack_data = &g.FontStack.back(); + SetCurrentFont(font_stack_data->Font, font_stack_data->FontSizeBeforeScaling, font_stack_data->FontSizeAfterScaling); + g.FontStack.pop_back(); +} + //----------------------------------------------------------------------------- // [SECTION] ID STACK //----------------------------------------------------------------------------- @@ -10515,12 +10876,16 @@ void ImGui::UpdateInputEvents(bool trickle_fast_inputs) if (trickle_interleaved_nonchar_keys_and_text && (text_inputted && !key_is_potentially_for_char_input)) break; + if (key_data->Down != e->Key.Down) // Analog change only do not trigger this, so it won't block e.g. further mouse pos events testing key_changed. + { + key_changed = true; + key_changed_mask.SetBit(key_data_index); + if (trickle_interleaved_nonchar_keys_and_text && !key_is_potentially_for_char_input) + key_changed_nonchar = true; + } + key_data->Down = e->Key.Down; key_data->AnalogValue = e->Key.AnalogValue; - key_changed = true; - key_changed_mask.SetBit(key_data_index); - if (trickle_interleaved_nonchar_keys_and_text && !key_is_potentially_for_char_input) - key_changed_nonchar = true; } else if (e->Type == ImGuiInputEventType_Text) { @@ -10817,36 +11182,44 @@ bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, si return !error; } -// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell) -// This is causing issues and ambiguity and we need to retire that. -// See https://github.com/ocornut/imgui/issues/5548 for more details. -// [Scenario 1] +// Until 1.89 (August 2022, IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos()/SetCursorScreenPos() +// to extend contents size of our parent container (e.g. window contents size, which is used for auto-resizing +// windows, table column contents size used for auto-resizing columns, group size). +// This was causing issues and ambiguities and we needed to retire that. +// From 1.89, extending contents size boundaries REQUIRES AN ITEM TO BE SUBMITTED. +// // Previously this would make the window content size ~200x200: -// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK +// Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); // NOT OK ANYMORE // Instead, please submit an item: // Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK // Alternative: // Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK -// [Scenario 2] -// For reference this is one of the issue what we aim to fix with this change: -// BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup() -// The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller! -// While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue. +// +// The assert below detects when the _last_ call in a window was a SetCursorPos() not followed by an Item, +// and with a position that would grow the parent contents size. +// +// Advanced: +// - For reference, old logic was causing issues because it meant that SetCursorScreenPos(GetCursorScreenPos()) +// had a side-effect on layout! In particular this caused problem to compute group boundaries. +// e.g. BeginGroup() + SomeItem() + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup() would cause the +// group to be taller because auto-sizing generally adds padding on bottom and right side. +// - While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. +// Using vertical alignment patterns would frequently trigger this sorts of issue. +// - See https://github.com/ocornut/imgui/issues/5548 for more details. void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(window->DC.IsSetPos); window->DC.IsSetPos = false; -#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y) return; if (window->SkipItems) return; - IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent."); -#else - window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); -#endif + IM_ASSERT_USER_ERROR(0, "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries.\nPlease submit an item e.g. Dummy() afterwards in order to grow window/parent boundaries."); + + // For reference, the old behavior was essentially: + //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } static void ImGui::ErrorCheckNewFrameSanityChecks() @@ -10874,7 +11247,6 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!"); IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?"); IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!"); - IM_ASSERT(g.IO.Fonts->IsBuilt() && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()"); IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!"); IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!"); IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations @@ -10882,12 +11254,16 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() IM_ASSERT(g.Style.WindowBorderHoverPadding > 0.0f && "Invalid style setting!"); // Required otherwise cannot resize from borders. IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right); IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right); + IM_ASSERT(g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesNone || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesFull || g.Style.TreeLinesFlags == ImGuiTreeNodeFlags_DrawLinesToNodes); // Error handling: we do not accept 100% silent recovery! Please contact me if you feel this is getting in your way. if (g.IO.ConfigErrorRecovery) IM_ASSERT(g.IO.ConfigErrorRecoveryEnableAssert || g.IO.ConfigErrorRecoveryEnableDebugLog || g.IO.ConfigErrorRecoveryEnableTooltip || g.ErrorCallback != NULL); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + if (g.IO.FontGlobalScale > 1.0f) + IM_ASSERT(g.Style.FontScaleMain == 1.0f && "Since 1.92: use style.FontScaleMain instead of g.IO.FontGlobalScale!"); + // Remap legacy names if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) { @@ -10899,6 +11275,16 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() g.IO.ConfigNavCaptureKeyboard = false; g.IO.ConfigFlags &= ~ImGuiConfigFlags_NavNoCaptureKeyboard; } + if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) + { + g.IO.ConfigDpiScaleFonts = false; + g.IO.ConfigFlags &= ~ImGuiConfigFlags_DpiEnableScaleFonts; + } + if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports) + { + g.IO.ConfigDpiScaleViewports = false; + g.IO.ConfigFlags &= ~ImGuiConfigFlags_DpiEnableScaleViewports; + } // Remap legacy clipboard handlers (OBSOLETED in 1.91.1, August 2024) if (g.IO.GetClipboardTextFn != NULL && (g.PlatformIO.Platform_GetClipboardTextFn == NULL || g.PlatformIO.Platform_GetClipboardTextFn == Platform_GetClipboardTextFn_DefaultImpl)) @@ -11157,9 +11543,9 @@ void ImGui::ErrorCheckEndFrameFinalizeErrorTooltip() { #ifndef IMGUI_DISABLE_DEBUG_TOOLS ImGuiContext& g = *GImGui; - if (g.DebugDrawIdConflicts != 0 && g.IO.KeyCtrl == false) + if (g.DebugDrawIdConflictsId != 0 && g.IO.KeyCtrl == false) g.DebugDrawIdConflictsCount = g.HoveredIdPreviousFrameItemCount; - if (g.DebugDrawIdConflicts != 0 && g.DebugItemPickerActive == false && BeginErrorTooltip()) + if (g.DebugDrawIdConflictsId != 0 && g.DebugItemPickerActive == false && BeginErrorTooltip()) { Text("Programmer error: %d visible items with conflicting ID!", g.DebugDrawIdConflictsCount); BulletText("Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!"); @@ -11328,6 +11714,21 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGu // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something". // READ THE FAQ: https://dearimgui.com/faq IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!"); + + // [DEBUG] Highlight all conflicts WITHOUT needing to hover. THIS WILL SLOW DOWN DEAR IMGUI. DON'T KEEP ACTIVATED. + // This will only work for items submitted with ItemAdd(). Some very rare/odd/unrecommended code patterns are calling ButtonBehavior() without ItemAdd(). +#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS + if ((g.LastItemData.ItemFlags & ImGuiItemFlags_AllowDuplicateId) == 0) + { + int* p_alive = g.DebugDrawIdConflictsAliveCount.GetIntRef(id, -1); // Could halve lookups if we knew ImGuiStorage can store 64-bit, or by storing FrameCount as 30-bits + highlight as 2-bits. But the point is that we should not pretend that this is fast. + int* p_highlight = g.DebugDrawIdConflictsHighlightSet.GetIntRef(id, -1); + if (*p_alive == g.FrameCount) + *p_highlight = g.FrameCount; + *p_alive = g.FrameCount; + if (*p_highlight >= g.FrameCount - 1) + window->DrawList->AddRect(bb.Min - ImVec2(1, 1), bb.Max + ImVec2(1, 1), IM_COL32(255, 0, 0, 255), 0.0f, ImDrawFlags_None, 2.0f); + } +#endif } //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG] //if ((g.LastItemData.ItemFlags & ImGuiItemFlags_NoNav) == 0) @@ -11809,7 +12210,7 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window) } scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]); } - scroll[axis] = IM_ROUND(ImMax(scroll[axis], 0.0f)); + scroll[axis] = ImRound64(ImMax(scroll[axis], 0.0f)); if (!window->Collapsed && !window->SkipItems) scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]); } @@ -12042,7 +12443,7 @@ bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags ext // - offset visibility to increase visibility around mouse. // - never clamp within outer viewport boundary. // We call SetNextWindowPos() to enforce position and disable clamping. - // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones). + // See FindBestWindowPosForPopup() for positioning logic of other tooltips (not drag and drop ones). //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding; const bool is_touchscreen = (g.IO.MouseSource == ImGuiMouseSource_TouchScreen); if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasPos) == 0) @@ -12507,8 +12908,11 @@ void ImGui::EndPopup() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls - IM_ASSERT(g.BeginPopupStack.Size > 0); + if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || g.BeginPopupStack.Size == 0) + { + IM_ASSERT_USER_ERROR(0, "Calling EndPopup() too many times or in wrong window!"); + return; + } // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests) if (g.NavWindow == window) @@ -13496,8 +13900,8 @@ void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result) NavUpdateAnyRequestFlag(); } -// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere -void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiTreeNodeStackData* tree_node_data) +// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsToParent +void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, const ImGuiTreeNodeStackData* tree_node_data) { ImGuiContext& g = *GImGui; g.NavMoveScoringItems = false; @@ -14044,7 +14448,7 @@ void ImGui::NavUpdateCreateMoveRequest() //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG] } g.NavScoringRect = scoring_rect; - g.NavScoringNoClipRect.Add(scoring_rect); + //g.NavScoringNoClipRect.Add(scoring_rect); } void ImGui::NavUpdateCreateTabbingRequest() @@ -14263,7 +14667,7 @@ static float ImGui::NavUpdatePageUpPageDown() if (g.NavLayer != ImGuiNavLayer_Main) NavRestoreLayer(ImGuiNavLayer_Main); - if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY) + if ((window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Main)) == 0 && window->DC.NavWindowHasScrollY) { // Fallback manual-scroll when window has no navigable item if (IsKeyPressed(ImGuiKey_PageUp, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner)) @@ -14495,17 +14899,18 @@ static void ImGui::NavUpdateWindowing() const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id); const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id); - const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_None); + const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && Shortcut(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_RouteAlways, owner_id); const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard! bool just_started_windowing_from_null_focus = false; if (start_windowing_with_gamepad || start_windowing_with_keyboard) if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1)) { - g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // Current location + if (start_windowing_with_keyboard || g.ConfigNavWindowingWithGamepad) + g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // Current location g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f; g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f); g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer - g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad; + g.NavWindowingInputSource = g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad; if (g.NavWindow == NULL) just_started_windowing_from_null_focus = true; @@ -14515,18 +14920,22 @@ static void ImGui::NavUpdateWindowing() } // Gamepad update - g.NavWindowingTimer += io.DeltaTime; - if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad) + if ((g.NavWindowingTarget || g.NavWindowingToggleLayer) && g.NavWindowingInputSource == ImGuiInputSource_Gamepad) { - // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise - g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); - - // Select window to focus - const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1); - if (focus_change_dir != 0 && !just_started_windowing_from_null_focus) + if (g.NavWindowingTarget != NULL) { - NavUpdateWindowingTarget(focus_change_dir); - g.NavWindowingHighlightAlpha = 1.0f; + // Highlight only appears after a brief time holding the button, so that a fast tap on ImGuiKey_NavGamepadMenu (to toggle NavLayer) doesn't add visual noise + // However inputs are accepted immediately, so you press ImGuiKey_NavGamepadMenu + L1/R1 fast. + g.NavWindowingTimer += io.DeltaTime; + g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); + + // Select window to focus + const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1); + if (focus_change_dir != 0 && !just_started_windowing_from_null_focus) + { + NavUpdateWindowingTarget(focus_change_dir); + g.NavWindowingHighlightAlpha = 1.0f; + } } // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most) @@ -14538,15 +14947,17 @@ static void ImGui::NavUpdateWindowing() else if (!g.NavWindowingToggleLayer) apply_focus_window = g.NavWindowingTarget; g.NavWindowingTarget = NULL; + g.NavWindowingToggleLayer = false; } } // Keyboard: Focus - if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard) + if (g.NavWindowingTarget && g.NavWindowingInputSource == ImGuiInputSource_Keyboard) { // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_; IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows. + g.NavWindowingTimer += io.DeltaTime; g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f if ((keyboard_next_window || keyboard_prev_window) && !just_started_windowing_from_null_focus) NavUpdateWindowingTarget(keyboard_next_window ? -1 : +1); @@ -14564,10 +14975,10 @@ static void ImGui::NavUpdateWindowing() windowing_toggle_layer_start = true; g.NavWindowingToggleLayer = true; g.NavWindowingToggleKey = windowing_toggle_key; - g.NavInputSource = ImGuiInputSource_Keyboard; + g.NavWindowingInputSource = g.NavInputSource = ImGuiInputSource_Keyboard; break; } - if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard) + if (g.NavWindowingToggleLayer && g.NavWindowingInputSource == ImGuiInputSource_Keyboard) { // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370) // We cancel toggling nav layer when other modifiers are pressed. (See #4439) @@ -15033,7 +15444,7 @@ void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_r bool push_clip_rect = !window->ClipRect.Contains(bb_display); if (push_clip_rect) window->DrawList->PushClipRectFullScreen(); - window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f); + window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f); // FIXME-DPI if (push_clip_rect) window->DrawList->PopClipRect(); } @@ -15850,6 +16261,7 @@ static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window) void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos, const ImVec2& old_size, const ImVec2& new_size) { ImGuiContext& g = *GImGui; + //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] TranslateWindowsInViewport 0x%08X\n", viewport->ID); IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows)); // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently @@ -15858,7 +16270,7 @@ void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& o // One problem with this is that most Win32 applications doesn't update their render while dragging, // and so the window will appear to teleport when releasing the mouse. const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable); - ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size); + ImRect test_still_fit_rect(old_pos, old_pos + old_size); ImVec2 delta_pos = new_pos - old_pos; for (ImGuiWindow* window : g.Windows) // FIXME-OPT if (translate_all_windows || (window->Viewport == viewport && (old_size == new_size || test_still_fit_rect.Contains(window->Rect())))) @@ -15869,6 +16281,7 @@ void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& o void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale) { ImGuiContext& g = *GImGui; + //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] ScaleWindowsInViewport 0x%08X\n", viewport->ID); if (viewport->Window) { ScaleWindow(viewport->Window, scale); @@ -15937,7 +16350,7 @@ static void ImGui::UpdateViewportsNewFrame() // Focused viewport has changed? if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID) { - IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID); + IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X '%s', attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID, focused_viewport->Window ? focused_viewport->Window->Name : "n/a"); const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId); const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false); @@ -15976,10 +16389,12 @@ static void ImGui::UpdateViewportsNewFrame() IM_ASSERT(main_viewport->Window == NULL); ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f); ImVec2 main_viewport_size = g.IO.DisplaySize; + ImVec2 main_viewport_framebuffer_scale = g.IO.DisplayFramebufferScale; if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized)) { - main_viewport_pos = main_viewport->Pos; // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path) + main_viewport_pos = main_viewport->Pos; // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path) main_viewport_size = main_viewport->Size; + main_viewport_framebuffer_scale = main_viewport->FramebufferScale; } AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows); @@ -16011,6 +16426,8 @@ static void ImGui::UpdateViewportsNewFrame() viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport); if (viewport->PlatformRequestResize) viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport); + if (g.PlatformIO.Platform_GetWindowFramebufferScale != NULL) + viewport->FramebufferScale = g.PlatformIO.Platform_GetWindowFramebufferScale(viewport); } } @@ -16052,7 +16469,7 @@ static void ImGui::UpdateViewportsNewFrame() if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale) { float scale_factor = new_dpi_scale / viewport->DpiScale; - if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports) + if (g.IO.ConfigDpiScaleViewports) ScaleWindowsInViewport(viewport, scale_factor); //if (viewport == GetMainViewport()) // g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor); @@ -16216,10 +16633,7 @@ ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const // Store initial DpiScale before the OS platform window creation, based on expected monitor data. // This is so we can select an appropriate font size on the first frame of our window lifetime - if (viewport->PlatformMonitor != -1) - viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale; - else - viewport->DpiScale = 1.0f; + viewport->DpiScale = GetViewportPlatformMonitor(viewport)->DpiScale; } viewport->Window = window; @@ -17213,7 +17627,7 @@ static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx) { ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n]; ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID); - if (data->CountWindows > 1) + if (data == NULL || data->CountWindows > 1) continue; ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId); @@ -20913,7 +21327,8 @@ static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImG // - RenderViewportsThumbnails() [Internal] // - DebugTextEncoding() // - MetricsHelpMarker() [Internal] -// - ShowFontAtlas() [Internal] +// - ShowFontAtlas() [Internal but called by Demo!] +// - DebugNodeTexture() [Internal] // - ShowMetricsWindow() // - DebugNodeColumns() [Internal] // - DebugNodeDockNode() [Internal] @@ -21075,10 +21490,12 @@ void ImGui::DebugTextEncoding(const char* str) Text("0x%02X", (int)(unsigned char)p[byte_index]); } TableNextColumn(); - if (GetFont()->FindGlyphNoFallback((ImWchar)c)) - TextUnformatted(p, p + c_utf8_len); - else - TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]"); + TextUnformatted(p, p + c_utf8_len); + if (!GetFont()->IsGlyphInFont((ImWchar)c)) + { + SameLine(); + TextUnformatted("[missing]"); + } TableNextColumn(); Text("U+%04X", (int)c); p += c_utf8_len; @@ -21126,6 +21543,14 @@ static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTex return buf; } +static const char* FormatTextureIDForDebugDisplay(char* buf, int buf_size, const ImDrawCmd* cmd) +{ + char* buf_end = buf + buf_size; + if (cmd->TexRef._TexData != NULL) + buf += ImFormatString(buf, buf_end - buf, "#%03d: ", cmd->TexRef._TexData->UniqueID); + return FormatTextureIDForDebugDisplay(buf, (int)(buf_end - buf), cmd->TexRef.GetTexID()); // Calling TexRef::GetTexID() to avoid assert of cmd->GetTexID() +} + // Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds. static void MetricsHelpMarker(const char* desc) { @@ -21139,23 +21564,195 @@ static void MetricsHelpMarker(const char* desc) } } +#ifdef IMGUI_ENABLE_FREETYPE +namespace ImGuiFreeType { IMGUI_API const ImFontLoader* GetFontLoader(); IMGUI_API bool DebugEditFontLoaderFlags(unsigned int* p_font_builder_flags); } +#endif + // [DEBUG] List fonts in a font atlas and display its texture void ImGui::ShowFontAtlas(ImFontAtlas* atlas) { + ImGuiContext& g = *GImGui; + ImGuiIO& io = g.IO; + ImGuiStyle& style = g.Style; + + BeginDisabled(); + CheckboxFlags("io.BackendFlags: RendererHasTextures", &io.BackendFlags, ImGuiBackendFlags_RendererHasTextures); + EndDisabled(); + ShowFontSelector("Font"); + //BeginDisabled((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0); + if (DragFloat("FontSizeBase", &style.FontSizeBase, 0.20f, 5.0f, 100.0f, "%.0f")) + style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work. + SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize()); + SameLine(); MetricsHelpMarker("- This is scaling font only. General scaling will come later."); + DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 4.0f); + //BeginDisabled(io.ConfigDpiScaleFonts); + DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 4.0f); + //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten."); + //EndDisabled(); + if ((io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) + { + BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!"); + BulletText("For instructions, see:"); + SameLine(); + TextLinkOpenURL("docs/BACKENDS.md", "https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md"); + } + BulletText("Load a nice font for better results!"); + BulletText("Please submit feedback:"); + SameLine(); TextLinkOpenURL("#8465", "https://github.com/ocornut/imgui/issues/8465"); + BulletText("Read FAQ for more details:"); + SameLine(); TextLinkOpenURL("dearimgui.com/faq", "https://www.dearimgui.com/faq/"); + //EndDisabled(); + + SeparatorText("Font List"); + + ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; + Checkbox("Show font preview", &cfg->ShowFontPreview); + + // Font loaders + if (TreeNode("Loader", "Loader: \'%s\'", atlas->FontLoaderName ? atlas->FontLoaderName : "NULL")) + { + const ImFontLoader* loader_current = atlas->FontLoader; + BeginDisabled(!atlas->RendererHasTextures); +#ifdef IMGUI_ENABLE_STB_TRUETYPE + const ImFontLoader* loader_stbtruetype = ImFontAtlasGetFontLoaderForStbTruetype(); + if (RadioButton("stb_truetype", loader_current == loader_stbtruetype)) + atlas->SetFontLoader(loader_stbtruetype); +#else + BeginDisabled(); + RadioButton("stb_truetype", false); + SetItemTooltip("Requires #define IMGUI_ENABLE_STB_TRUETYPE"); + EndDisabled(); +#endif + SameLine(); +#ifdef IMGUI_ENABLE_FREETYPE + const ImFontLoader* loader_freetype = ImGuiFreeType::GetFontLoader(); + if (RadioButton("FreeType", loader_current == loader_freetype)) + atlas->SetFontLoader(loader_freetype); + if (loader_current == loader_freetype) + { + unsigned int loader_flags = atlas->FontLoaderFlags; + Text("Shared FreeType Loader Flags: 0x%08X", loader_flags); + if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags)) + { + for (ImFont* font : atlas->Fonts) + ImFontAtlasFontDestroyOutput(atlas, font); + atlas->FontLoaderFlags = loader_flags; + for (ImFont* font : atlas->Fonts) + ImFontAtlasFontInitOutput(atlas, font); + } + } +#else + BeginDisabled(); + RadioButton("FreeType", false); + SetItemTooltip("Requires #define IMGUI_ENABLE_FREETYPE + imgui_freetype.cpp."); + EndDisabled(); +#endif + EndDisabled(); + TreePop(); + } + + // Font list for (ImFont* font : atlas->Fonts) { PushID(font); DebugNodeFont(font); PopID(); } - if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight)) + + SeparatorText("Font Atlas"); + if (Button("Compact")) + atlas->CompactCache(); + SameLine(); + if (Button("Grow")) + ImFontAtlasTextureGrow(atlas); + SameLine(); + if (Button("Clear All")) + ImFontAtlasBuildClear(atlas); + SetItemTooltip("Destroy cache and custom rectangles."); + + for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++) { - ImGuiContext& g = *GImGui; - PushStyleVar(ImGuiStyleVar_ImageBorderSize, ImMax(1.0f, g.Style.ImageBorderSize)); - ImageWithBg(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); + ImTextureData* tex = atlas->TexList[tex_n]; + if (tex_n > 0) + SameLine(); + Text("Tex: %dx%d", tex->Width, tex->Height); + } + const int packed_surface_sqrt = (int)sqrtf((float)atlas->Builder->RectsPackedSurface); + const int discarded_surface_sqrt = (int)sqrtf((float)atlas->Builder->RectsDiscardedSurface); + Text("Packed rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsPackedCount, atlas->Builder->RectsPackedSurface, packed_surface_sqrt, packed_surface_sqrt); + Text("incl. Discarded rects: %d, area: about %d px ~%dx%d px", atlas->Builder->RectsDiscardedCount, atlas->Builder->RectsDiscardedSurface, discarded_surface_sqrt, discarded_surface_sqrt); + + ImFontAtlasRectId highlight_r_id = ImFontAtlasRectId_Invalid; + if (TreeNode("Rects Index", "Rects Index (%d)", atlas->Builder->RectsPackedCount)) // <-- Use count of used rectangles + { + PushStyleVar(ImGuiStyleVar_ImageBorderSize, 1.0f); + if (BeginTable("##table", 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY, ImVec2(0.0f, GetTextLineHeightWithSpacing() * 12))) + { + for (const ImFontAtlasRectEntry& entry : atlas->Builder->RectsIndex) + if (entry.IsUsed) + { + ImFontAtlasRectId id = ImFontAtlasRectId_Make(atlas->Builder->RectsIndex.index_from_ptr(&entry), entry.Generation); + ImFontAtlasRect r = {}; + atlas->GetCustomRect(id, &r); + const char* buf; + ImFormatStringToTempBuffer(&buf, NULL, "ID:%08X, used:%d, { w:%3d, h:%3d } { x:%4d, y:%4d }", id, entry.IsUsed, r.w, r.h, r.x, r.y); + TableNextColumn(); + Selectable(buf); + if (IsItemHovered()) + highlight_r_id = id; + TableNextColumn(); + Image(atlas->TexRef, ImVec2(r.w, r.h), r.uv0, r.uv1); + } + EndTable(); + } PopStyleVar(); TreePop(); } + + // Texture list + // (ensure the last texture always use the same ID, so we can keep it open neatly) + ImFontAtlasRect highlight_r; + if (highlight_r_id != ImFontAtlasRectId_Invalid) + atlas->GetCustomRect(highlight_r_id, &highlight_r); + for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++) + { + if (tex_n == atlas->TexList.Size - 1) + SetNextItemOpen(true, ImGuiCond_Once); + DebugNodeTexture(atlas->TexList[tex_n], atlas->TexList.Size - 1 - tex_n, (highlight_r_id != ImFontAtlasRectId_Invalid) ? &highlight_r : NULL); + } +} + +void ImGui::DebugNodeTexture(ImTextureData* tex, int int_id, const ImFontAtlasRect* highlight_rect) +{ + ImGuiContext& g = *GImGui; + PushID(int_id); + if (TreeNode("", "Texture #%03d (%dx%d pixels)", tex->UniqueID, tex->Width, tex->Height)) + { + ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; + Checkbox("Show used rect", &cfg->ShowTextureUsedRect); + PushStyleVar(ImGuiStyleVar_ImageBorderSize, ImMax(1.0f, g.Style.ImageBorderSize)); + ImVec2 p = GetCursorScreenPos(); + if (tex->WantDestroyNextFrame) + Dummy(ImVec2((float)tex->Width, (float)tex->Height)); + else + ImageWithBg(tex->GetTexRef(), ImVec2((float)tex->Width, (float)tex->Height), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); + if (cfg->ShowTextureUsedRect) + GetWindowDrawList()->AddRect(ImVec2(p.x + tex->UsedRect.x, p.y + tex->UsedRect.y), ImVec2(p.x + tex->UsedRect.x + tex->UsedRect.w, p.y + tex->UsedRect.y + tex->UsedRect.h), IM_COL32(255, 0, 255, 255)); + if (highlight_rect != NULL) + { + ImRect r_outer(p.x, p.y, p.x + tex->Width, p.y + tex->Height); + ImRect r_inner(p.x + highlight_rect->x, p.y + highlight_rect->y, p.x + highlight_rect->x + highlight_rect->w, p.y + highlight_rect->y + highlight_rect->h); + RenderRectFilledWithHole(GetWindowDrawList(), r_outer, r_inner, IM_COL32(0, 0, 0, 100), 0.0f); + GetWindowDrawList()->AddRect(r_inner.Min - ImVec2(1, 1), r_inner.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255)); + } + PopStyleVar(); + + char texid_desc[30]; + Text("Status = %s (%d), Format = %s (%d), UseColors = %d", ImTextureDataGetStatusName(tex->Status), tex->Status, ImTextureDataGetFormatName(tex->Format), tex->Format, tex->UseColors); + Text("TexID = %s, BackendUserData = %p", FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), tex->TexID), tex->BackendUserData); + TreePop(); + } + PopID(); } void ImGui::ShowMetricsWindow(bool* p_open) @@ -21238,6 +21835,10 @@ void ImGui::ShowMetricsWindow(bool* p_open) } }; +#ifdef IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS + TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS is enabled.\nMust disable after use! Otherwise Dear ImGui will run slower.\n"); +#endif + // Tools if (TreeNode("Tools")) { @@ -21441,6 +22042,14 @@ void ImGui::ShowMetricsWindow(bool* p_open) TreePop(); } + // Details for Fonts + for (ImFontAtlas* atlas : g.FontAtlases) + if (TreeNode((void*)atlas, "Fonts (%d), Textures (%d)", atlas->Fonts.Size, atlas->TexList.Size)) + { + ShowFontAtlas(atlas); + TreePop(); + } + // Details for Popups if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size)) { @@ -21477,14 +22086,6 @@ void ImGui::ShowMetricsWindow(bool* p_open) TreePop(); } - // Details for Fonts - ImFontAtlas* atlas = g.IO.Fonts; - if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size)) - { - ShowFontAtlas(atlas); - TreePop(); - } - // Details for InputText if (TreeNode("InputText")) { @@ -22028,8 +22629,8 @@ void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, con continue; } - char texid_desc[20]; - FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TextureId); + char texid_desc[30]; + FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd); char buf[300]; ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); @@ -22118,19 +22719,39 @@ void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, co out_draw_list->Flags = backup_flags; } +// [DEBUG] Compute mask of inputs with the same codepoint. +static int CalcFontGlyphSrcOverlapMask(ImFontAtlas* atlas, ImFont* font, unsigned int codepoint) +{ + int mask = 0, count = 0; + for (int src_n = 0; src_n < font->Sources.Size; src_n++) + { + ImFontConfig* src = font->Sources[src_n]; + if (!(src->FontLoader ? src->FontLoader : atlas->FontLoader)->FontSrcContainsGlyph(atlas, src, (ImWchar)codepoint)) + continue; + mask |= (1 << src_n); + count++; + } + return count > 1 ? mask : 0; +} + // [DEBUG] Display details for a single font, called by ShowStyleEditor(). void ImGui::DebugNodeFont(ImFont* font) { - bool opened = TreeNode(font, "Font: \"%s\": %.2f px, %d glyphs, %d sources(s)", - font->Sources ? font->Sources[0].Name : "", font->FontSize, font->Glyphs.Size, font->SourcesCount); + ImGuiContext& g = *GImGui; + ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; + ImFontAtlas* atlas = font->ContainerAtlas; + bool opened = TreeNode(font, "Font: \"%s\": %d sources(s)", font->GetDebugName(), font->Sources.Size); // Display preview text if (!opened) Indent(); Indent(); - PushFont(font); - Text("The quick brown fox jumps over the lazy dog"); - PopFont(); + if (cfg->ShowFontPreview) + { + PushFont(font, 0.0f); + Text("The quick brown fox jumps over the lazy dog"); + PopFont(); + } if (!opened) { Unindent(); @@ -22139,90 +22760,177 @@ void ImGui::DebugNodeFont(ImFont* font) } if (SmallButton("Set as default")) GetIO().FontDefault = font; + SameLine(); + BeginDisabled(atlas->Fonts.Size <= 1 || atlas->Locked); + if (SmallButton("Remove")) + atlas->RemoveFont(font); + EndDisabled(); + SameLine(); + if (SmallButton("Clear bakes")) + ImFontAtlasFontDiscardBakes(atlas, font, 0); + SameLine(); + if (SmallButton("Clear unused")) + ImFontAtlasFontDiscardBakes(atlas, font, 2); // Display details +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS SetNextItemWidth(GetFontSize() * 8); DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); - SameLine(); MetricsHelpMarker( + /*SameLine(); MetricsHelpMarker( "Note that the default embedded font is NOT meant to be scaled.\n\n" "Font are currently rendered into bitmaps at a given size at the time of building the atlas. " "You may oversample them to get some flexibility with scaling. " "You can also render at multiple sizes and select which one to use at runtime.\n\n" - "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)"); - Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent); + "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");*/ +#endif + char c_str[5]; Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar); Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar); - const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface); - Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt); - for (int config_i = 0; config_i < font->SourcesCount; config_i++) - if (font->Sources) - { - const ImFontConfig* src = &font->Sources[config_i]; - int oversample_h, oversample_v; - ImFontAtlasBuildGetOversampleFactors(src, &oversample_h, &oversample_v); - BulletText("Input %d: \'%s\', Oversample: (%d=>%d,%d=>%d), PixelSnapH: %d, Offset: (%.1f,%.1f)", - config_i, src->Name, src->OversampleH, oversample_h, src->OversampleV, oversample_v, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y); - } - // Display all glyphs of the fonts in separate pages of 256 characters + for (int src_n = 0; src_n < font->Sources.Size; src_n++) { - if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size)) + ImFontConfig* src = font->Sources[src_n]; + if (TreeNode(src, "Input %d: \'%s\', Oversample: %d,%d, PixelSnapH: %d, Offset: (%.1f,%.1f)", + src_n, src->Name, src->OversampleH, src->OversampleV, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y)) { - ImDrawList* draw_list = GetWindowDrawList(); - const ImU32 glyph_col = GetColorU32(ImGuiCol_Text); - const float cell_size = font->FontSize * 1; - const float cell_spacing = GetStyle().ItemSpacing.y; - for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256) + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + Text("Loader: '%s'", loader->Name ? loader->Name : "N/A"); +#ifdef IMGUI_ENABLE_FREETYPE + if (loader->Name != NULL && strcmp(loader->Name, "FreeType") == 0) { - // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k) - // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT - // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here) - if (!(base & 8191) && font->IsGlyphRangeUnused(base, base + 8191)) + unsigned int loader_flags = src->FontLoaderFlags; + Text("FreeType Loader Flags: 0x%08X", loader_flags); + if (ImGuiFreeType::DebugEditFontLoaderFlags(&loader_flags)) { - base += 8192 - 256; - continue; + ImFontAtlasFontDestroyOutput(atlas, font); + src->FontLoaderFlags = loader_flags; + ImFontAtlasFontInitOutput(atlas, font); } - - int count = 0; - for (unsigned int n = 0; n < 256; n++) - if (font->FindGlyphNoFallback((ImWchar)(base + n))) - count++; - if (count <= 0) - continue; - if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph")) - continue; - - // Draw a 16x16 grid of glyphs - ImVec2 base_pos = GetCursorScreenPos(); - for (unsigned int n = 0; n < 256; n++) - { - // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions - // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string. - ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing)); - ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size); - const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n)); - draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50)); - if (!glyph) - continue; - font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n)); - if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip()) - { - DebugNodeFontGlyph(font, glyph); - EndTooltip(); - } - } - Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16)); - TreePop(); } +#endif TreePop(); } } + if (font->Sources.Size > 1 && TreeNode("Input Glyphs Overlap Detection Tool")) + { + TextWrapped("- First Input that contains the glyph is used.\n" + "- Use ImFontConfig::GlyphExcludeRanges[] to specify ranges to ignore glyph in given Input.\n- Prefer using a small number of ranges as the list is scanned every time a new glyph is loaded,\n - e.g. GlyphExcludeRanges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };\n- This tool doesn't cache results and is slow, don't keep it open!"); + if (BeginTable("table", 2)) + { + for (unsigned int c = 0; c < 0x10000; c++) + if (int overlap_mask = CalcFontGlyphSrcOverlapMask(atlas, font, c)) + { + unsigned int c_end = c + 1; + while (c_end < 0x10000 && CalcFontGlyphSrcOverlapMask(atlas, font, c_end) == overlap_mask) + c_end++; + if (TableNextColumn() && TreeNode((void*)(intptr_t)c, "U+%04X-U+%04X: %d codepoints in %d inputs", c, c_end - 1, c_end - c, ImCountSetBits(overlap_mask))) + { + char utf8_buf[5]; + for (unsigned int n = c; n < c_end; n++) + BulletText("Codepoint U+%04X (%s)", n, ImTextCharToUtf8(utf8_buf, n)); + TreePop(); + } + TableNextColumn(); + for (int src_n = 0; src_n < font->Sources.Size; src_n++) + if (overlap_mask & (1 << src_n)) + { + Text("%d ", src_n); + SameLine(); + } + c = c_end - 1; + } + EndTable(); + } + TreePop(); + } + + // Display all glyphs of the fonts in separate pages of 256 characters + for (int baked_n = 0; baked_n < atlas->Builder->BakedPool.Size; baked_n++) + { + ImFontBaked* baked = &atlas->Builder->BakedPool[baked_n]; + if (baked->ContainerFont != font) + continue; + PushID(baked_n); + if (TreeNode("Glyphs", "Baked at { %.2fpx, d.%.2f }: %d glyphs%s", baked->Size, baked->RasterizerDensity, baked->Glyphs.Size, (baked->LastUsedFrame < atlas->Builder->FrameCount - 1) ? " *Unused*" : "")) + { + if (SmallButton("Load all")) + for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base++) + baked->FindGlyph((ImWchar)base); + + const int surface_sqrt = (int)ImSqrt((float)baked->MetricsTotalSurface); + Text("Ascent: %f, Descent: %f, Ascent-Descent: %f", baked->Ascent, baked->Descent, baked->Ascent - baked->Descent); + Text("Texture Area: about %d px ~%dx%d px", baked->MetricsTotalSurface, surface_sqrt, surface_sqrt); + for (int src_n = 0; src_n < font->Sources.Size; src_n++) + { + ImFontConfig* src = font->Sources[src_n]; + int oversample_h, oversample_v; + ImFontAtlasBuildGetOversampleFactors(src, baked, &oversample_h, &oversample_v); + BulletText("Input %d: \'%s\', Oversample: (%d=>%d,%d=>%d), PixelSnapH: %d, Offset: (%.1f,%.1f)", + src_n, src->Name, src->OversampleH, oversample_h, src->OversampleV, oversample_v, src->PixelSnapH, src->GlyphOffset.x, src->GlyphOffset.y); + } + + DebugNodeFontGlyphesForSrcMask(font, baked, ~0); + TreePop(); + } + PopID(); + } TreePop(); Unindent(); } -void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph) +void ImGui::DebugNodeFontGlyphesForSrcMask(ImFont* font, ImFontBaked* baked, int src_mask) +{ + ImDrawList* draw_list = GetWindowDrawList(); + const ImU32 glyph_col = GetColorU32(ImGuiCol_Text); + const float cell_size = baked->Size * 1; + const float cell_spacing = GetStyle().ItemSpacing.y; + for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256) + { + // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k) + // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT + // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here) + if (!(base & 8191) && font->IsGlyphRangeUnused(base, base + 8191)) + { + base += 8192 - 256; + continue; + } + + int count = 0; + for (unsigned int n = 0; n < 256; n++) + if (const ImFontGlyph* glyph = baked->IsGlyphLoaded((ImWchar)(base + n)) ? baked->FindGlyph((ImWchar)(base + n)) : NULL) + if (src_mask & (1 << glyph->SourceIdx)) + count++; + if (count <= 0) + continue; + if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph")) + continue; + + // Draw a 16x16 grid of glyphs + ImVec2 base_pos = GetCursorScreenPos(); + for (unsigned int n = 0; n < 256; n++) + { + // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions + // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string. + ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing)); + ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size); + const ImFontGlyph* glyph = baked->IsGlyphLoaded((ImWchar)(base + n)) ? baked->FindGlyph((ImWchar)(base + n)) : NULL; + draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50)); + if (!glyph || (src_mask & (1 << glyph->SourceIdx)) == 0) + continue; + font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n)); + if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip()) + { + DebugNodeFontGlyph(font, glyph); + EndTooltip(); + } + } + Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16)); + TreePop(); + } +} + +void ImGui::DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph) { Text("Codepoint: U+%04X", glyph->Codepoint); Separator(); @@ -22230,6 +22938,12 @@ void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph) Text("AdvanceX: %.1f", glyph->AdvanceX); Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1); Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1); + if (glyph->PackId >= 0) + { + ImTextureRect* r = ImFontAtlasPackGetRect(font->ContainerAtlas, glyph->PackId); + Text("PackId: %d (%dx%d rect at %d,%d)", glyph->PackId, r->w, r->h, r->x, r->y); + } + Text("SourceIdx: %d", glyph->SourceIdx); } // [DEBUG] Display contents of ImGuiStorage @@ -22296,8 +23010,9 @@ void ImGui::DebugNodeViewport(ImGuiViewportP* viewport) if (open) { ImGuiWindowFlags flags = viewport->Flags; - BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Inset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%", + BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nFrameBufferScale: (%.2f,%.2f)\nWorkArea Inset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%", viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y, + viewport->FramebufferScale.x, viewport->FramebufferScale.y, viewport->WorkInsetMin.x, viewport->WorkInsetMin.y, viewport->WorkInsetMax.x, viewport->WorkInsetMax.y, viewport->PlatformMonitor, viewport->DpiScale * 100.0f); if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } } @@ -22442,9 +23157,9 @@ void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int wi ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext); //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name); DebugNodeWindow(window, buf); - Indent(); + TreePush(buf); DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window); - Unindent(); + TreePop(); } } @@ -22537,7 +23252,7 @@ void ImGui::ShowDebugLogWindow(bool* p_open) ShowDebugLogFlag("Docking", ImGuiDebugLogFlags_EventDocking); ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus); ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO); - //ShowDebugLogFlag("Font", ImGuiDebugLogFlags_EventFont); + ShowDebugLogFlag("Font", ImGuiDebugLogFlags_EventFont); ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav); ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup); ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection); @@ -22924,6 +23639,7 @@ void ImGui::DebugNodeColumns(ImGuiOldColumns*) {} void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {} void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {} void ImGui::DebugNodeFont(ImFont*) {} +void ImGui::DebugNodeFontGlyphesForSrcMask(ImFont*, ImFontBaked*, int) {} void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {} void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {} void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {} @@ -22938,6 +23654,40 @@ void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {} #endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS +#if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS) +// Demo helper function to select among loaded fonts. +// Here we use the regular BeginCombo()/EndCombo() api which is the more flexible one. +void ImGui::ShowFontSelector(const char* label) +{ + ImGuiIO& io = GetIO(); + ImFont* font_current = GetFont(); + if (BeginCombo(label, font_current->GetDebugName())) + { + for (ImFont* font : io.Fonts->Fonts) + { + PushID((void*)font); + if (Selectable(font->GetDebugName(), font == font_current)) + io.FontDefault = font; + if (font == font_current) + SetItemDefaultFocus(); + PopID(); + } + EndCombo(); + } + SameLine(); + if (io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) + MetricsHelpMarker( + "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n" + "- Read FAQ and docs/FONTS.md for more details."); + else + MetricsHelpMarker( + "- Load additional fonts with io.Fonts->AddFontXXX() functions.\n" + "- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n" + "- Read FAQ and docs/FONTS.md for more details.\n" + "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame()."); +} +#endif // #if !defined(IMGUI_DISABLE_DEMO_WINDOWS) || !defined(IMGUI_DISABLE_DEBUG_TOOLS) + //----------------------------------------------------------------------------- // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed. diff --git a/lib/third_party/imgui/imgui/source/imgui_demo.cpp b/lib/third_party/imgui/imgui/source/imgui_demo.cpp index 6f0a4ab1b..88ea87656 100644 --- a/lib/third_party/imgui/imgui/source/imgui_demo.cpp +++ b/lib/third_party/imgui/imgui/source/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9b +// dear imgui, v1.92.1 // (demo code) // Help: @@ -82,6 +82,7 @@ Index of this file: // [SECTION] DemoWindowWidgetsDisableBlocks() // [SECTION] DemoWindowWidgetsDragAndDrop() // [SECTION] DemoWindowWidgetsDragsAndSliders() +// [SECTION] DemoWindowWidgetsFonts() // [SECTION] DemoWindowWidgetsImages() // [SECTION] DemoWindowWidgetsListBoxes() // [SECTION] DemoWindowWidgetsMultiComponents() @@ -425,9 +426,19 @@ void ImGui::ShowDemoWindow(bool* p_open) return; } - // Most "big" widgets share a common width settings by default. See 'Demo->Layout->Widgets Width' for details. - ImGui::PushItemWidth(ImGui::GetFontSize() * -12); // e.g. Leave a fixed amount of width for labels (by passing a negative value), the rest goes to widgets. - //ImGui::PushItemWidth(-ImGui::GetWindowWidth() * 0.35f); // e.g. Use 2/3 of the space for widgets and 1/3 for labels (right align) + // Most framed widgets share a common width settings. Remaining width is used for the label. + // The width of the frame may be changed with PushItemWidth() or SetNextItemWidth(). + // - Positive value for absolute size, negative value for right-alignment. + // - The default value is about GetWindowWidth() * 0.65f. + // - See 'Demo->Layout->Widgets Width' for details. + // Here we change the frame width based on how much width we want to give to the label. + const float label_width_base = ImGui::GetFontSize() * 12; // Some amount of width for label, based on font size. + const float label_width_max = ImGui::GetContentRegionAvail().x * 0.40f; // ...but always leave some room for framed widgets. + const float label_width = IM_MIN(label_width_base, label_width_max); + ImGui::PushItemWidth(-label_width); // Right-align: framed items will leave 'label_width' available for the label. + //ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x * 0.40f); // e.g. Use 40% width for framed widgets, leaving 60% width for labels. + //ImGui::PushItemWidth(-ImGui::GetContentRegionAvail().x * 0.40f); // e.g. Use 40% width for labels, leaving 60% width for framed widgets. + //ImGui::PushItemWidth(ImGui::GetFontSize() * -12); // e.g. Use XXX width for labels, leaving the rest for framed widgets. // Menu Bar DemoWindowMenuBar(&demo_data); @@ -548,6 +559,12 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::Unindent(); } + //ImGui::SeparatorText("DPI/Scaling"); + //ImGui::Checkbox("io.ConfigDpiScaleFonts", &io.ConfigDpiScaleFonts); + //ImGui::SameLine(); HelpMarker("Experimental: Automatically update style.FontScaleDpi when Monitor DPI changes. This will scale fonts but NOT style sizes/padding for now."); + //ImGui::Checkbox("io.ConfigDpiScaleViewports", &io.ConfigDpiScaleViewports); + //ImGui::SameLine(); HelpMarker("Experimental: Scale Dear ImGui and Platform Windows when Monitor DPI changes."); + ImGui::SeparatorText("Windows"); ImGui::Checkbox("io.ConfigWindowsResizeFromEdges", &io.ConfigWindowsResizeFromEdges); ImGui::SameLine(); HelpMarker("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires ImGuiBackendFlags_HasMouseCursors for better mouse cursor feedback."); @@ -622,6 +639,7 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::CheckboxFlags("io.BackendFlags: PlatformHasViewports", &io.BackendFlags, ImGuiBackendFlags_PlatformHasViewports); ImGui::CheckboxFlags("io.BackendFlags: HasMouseHoveredViewport",&io.BackendFlags, ImGuiBackendFlags_HasMouseHoveredViewport); ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", &io.BackendFlags, ImGuiBackendFlags_RendererHasVtxOffset); + ImGui::CheckboxFlags("io.BackendFlags: RendererHasTextures", &io.BackendFlags, ImGuiBackendFlags_RendererHasTextures); ImGui::CheckboxFlags("io.BackendFlags: RendererHasViewports", &io.BackendFlags, ImGuiBackendFlags_RendererHasViewports); ImGui::EndDisabled(); @@ -629,8 +647,8 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::Spacing(); } - IMGUI_DEMO_MARKER("Configuration/Style"); - if (ImGui::TreeNode("Style")) + IMGUI_DEMO_MARKER("Configuration/Style, Fonts"); + if (ImGui::TreeNode("Style, Fonts")) { ImGui::Checkbox("Style Editor", &demo_data.ShowStyleEditor); ImGui::SameLine(); @@ -890,6 +908,9 @@ static void DemoWindowWidgetsBasic() ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine(); ImGui::RadioButton("radio c", &e, 2); + ImGui::AlignTextToFramePadding(); + ImGui::TextLinkOpenURL("Hyperlink", "https://github.com/ocornut/imgui/wiki/Error-Handling"); + // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. IMGUI_DEMO_MARKER("Widgets/Basic/Buttons (Colored)"); for (int i = 0; i < 7; i++) @@ -1779,6 +1800,25 @@ static void DemoWindowWidgetsDragsAndSliders() } } +//----------------------------------------------------------------------------- +// [SECTION] DemoWindowWidgetsFonts() +//----------------------------------------------------------------------------- + +// Forward declare ShowFontAtlas() which isn't worth putting in public API yet +namespace ImGui { IMGUI_API void ShowFontAtlas(ImFontAtlas* atlas); } + +static void DemoWindowWidgetsFonts() +{ + IMGUI_DEMO_MARKER("Widgets/Fonts"); + if (ImGui::TreeNode("Fonts")) + { + ImFontAtlas* atlas = ImGui::GetIO().Fonts; + ImGui::ShowFontAtlas(atlas); + // FIXME-NEWATLAS: Provide a demo to add/create a procedural font? + ImGui::TreePop(); + } +} + //----------------------------------------------------------------------------- // [SECTION] DemoWindowWidgetsImages() //----------------------------------------------------------------------------- @@ -1795,13 +1835,12 @@ static void DemoWindowWidgetsImages() "Hover the texture for a zoomed view!"); // Below we are displaying the font texture because it is the only texture we have access to inside the demo! - // Remember that ImTextureID is just storage for whatever you want it to be. It is essentially a value that - // will be passed to the rendering backend via the ImDrawCmd structure. + // Read description about ImTextureID/ImTextureRef and FAQ for details about texture identifiers. // If you use one of the default imgui_impl_XXXX.cpp rendering backend, they all have comments at the top - // of their respective source file to specify what they expect to be stored in ImTextureID, for example: - // - The imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer + // of their respective source file to specify what they are using as texture identifier, for example: + // - The imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer. // - The imgui_impl_opengl3.cpp renderer expect a GLuint OpenGL texture identifier, etc. - // More: + // So with the DirectX11 backend, you call ImGui::Image() with a 'ID3D11ShaderResourceView*' cast to ImTextureID. // - If you decided that ImTextureID = MyEngineTexture*, then you can pass your MyEngineTexture* pointers // to ImGui::Image(), and gather width/height through your own functions, etc. // - You can use ShowMetricsWindow() to inspect the draw data that are being passed to your renderer, @@ -1809,14 +1848,19 @@ static void DemoWindowWidgetsImages() // - Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage(). // - Read https://github.com/ocornut/imgui/blob/master/docs/FAQ.md // - Read https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples - ImTextureID my_tex_id = io.Fonts->TexID; - float my_tex_w = (float)io.Fonts->TexWidth; - float my_tex_h = (float)io.Fonts->TexHeight; + + // Grab the current texture identifier used by the font atlas. + ImTextureRef my_tex_id = io.Fonts->TexRef; + + // Regular user code should never have to care about TexData-> fields, but since we want to display the entire texture here, we pull Width/Height from it. + float my_tex_w = (float)io.Fonts->TexData->Width; + float my_tex_h = (float)io.Fonts->TexData->Height; + { ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h); ImVec2 pos = ImGui::GetCursorScreenPos(); - ImVec2 uv_min = ImVec2(0.0f, 0.0f); // Top-left - ImVec2 uv_max = ImVec2(1.0f, 1.0f); // Lower-right + ImVec2 uv_min = ImVec2(0.0f, 0.0f); // Top-left + ImVec2 uv_max = ImVec2(1.0f, 1.0f); // Lower-right ImGui::PushStyleVar(ImGuiStyleVar_ImageBorderSize, IM_MAX(1.0f, ImGui::GetStyle().ImageBorderSize)); ImGui::ImageWithBg(my_tex_id, ImVec2(my_tex_w, my_tex_h), uv_min, uv_max, ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); if (ImGui::BeginItemTooltip()) @@ -2463,7 +2507,7 @@ static const char* ExampleNames[] = struct ExampleSelectionWithDeletion : ImGuiSelectionBasicStorage { // Find which item should be Focused after deletion. - // Call _before_ item submission. Retunr an index in the before-deletion item list, your item loop should call SetKeyboardFocusHere() on it. + // Call _before_ item submission. Return an index in the before-deletion item list, your item loop should call SetKeyboardFocusHere() on it. // The subsequent ApplyDeletionPostLoop() code will use it to apply Selection. // - We cannot provide this logic in core Dear ImGui because we don't have access to selection data. // - We don't actually manipulate the ImVector<> here, only in ApplyDeletionPostLoop(), but using similar API for consistency and flexibility. @@ -2566,7 +2610,7 @@ struct ExampleDualListBox { const int* a = (const int*)lhs; const int* b = (const int*)rhs; - return (*a - *b) > 0 ? +1 : -1; + return (*a - *b); } void SortItems(int n) { @@ -2574,7 +2618,7 @@ struct ExampleDualListBox } void Show() { - //ImGui::Checkbox("Sorted", &OptKeepSorted); + //if (ImGui::Checkbox("Sorted", &OptKeepSorted) && OptKeepSorted) { SortItems(0); SortItems(1); } if (ImGui::BeginTable("split", 3, ImGuiTableFlags_None)) { ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch); // Left side @@ -3046,7 +3090,7 @@ static void DemoWindowWidgetsSelectionAndMultiSelect(ImGuiDemoWindowData* demo_d static void DrawNode(ExampleTreeNode* node, ImGuiSelectionBasicStorage* selection) { ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; - tree_node_flags |= ImGuiTreeNodeFlags_NavLeftJumpsBackHere; // Enable pressing left to jump to parent + tree_node_flags |= ImGuiTreeNodeFlags_NavLeftJumpsToParent; // Enable pressing left to jump to parent if (node->Childs.Size == 0) tree_node_flags |= ImGuiTreeNodeFlags_Bullet | ImGuiTreeNodeFlags_Leaf; if (selection->Contains((ImGuiID)node->UID)) @@ -3585,6 +3629,43 @@ static void DemoWindowWidgetsText() ImGui::TreePop(); } + IMGUI_DEMO_MARKER("Widgets/Text/Font Size"); + if (ImGui::TreeNode("Font Size")) + { + ImGuiStyle& style = ImGui::GetStyle(); + const float global_scale = style.FontScaleMain * style.FontScaleDpi; + ImGui::Text("style.FontScaleMain = %0.2f", style.FontScaleMain); + ImGui::Text("style.FontScaleDpi = %0.2f", style.FontScaleDpi); + ImGui::Text("global_scale = ~%0.2f", global_scale); // This is not technically accurate as internal scales may apply, but conceptually let's pretend it is. + ImGui::Text("FontSize = %0.2f", ImGui::GetFontSize()); + + ImGui::SeparatorText(""); + static float custom_size = 16.0f; + ImGui::SliderFloat("custom_size", &custom_size, 10.0f, 100.0f, "%.0f"); + ImGui::Text("ImGui::PushFont(nullptr, custom_size);"); + ImGui::PushFont(NULL, custom_size); + ImGui::Text("FontSize = %.2f (== %.2f * global_scale)", ImGui::GetFontSize(), custom_size); + ImGui::PopFont(); + + ImGui::SeparatorText(""); + static float custom_scale = 1.0f; + ImGui::SliderFloat("custom_scale", &custom_scale, 0.5f, 4.0f, "%.2f"); + ImGui::Text("ImGui::PushFont(nullptr, style.FontSizeBase * custom_scale);"); + ImGui::PushFont(NULL, style.FontSizeBase * custom_scale); + ImGui::Text("FontSize = %.2f (== style.FontSizeBase * %.2f * global_scale)", ImGui::GetFontSize(), custom_scale); + ImGui::PopFont(); + + ImGui::SeparatorText(""); + for (float scaling = 0.5f; scaling <= 4.0f; scaling += 0.5f) + { + ImGui::PushFont(NULL, style.FontSizeBase * scaling); + ImGui::Text("FontSize = %.2f (== style.FontSizeBase * %.2f * global_scale)", ImGui::GetFontSize(), scaling); + ImGui::PopFont(); + } + + ImGui::TreePop(); + } + IMGUI_DEMO_MARKER("Widgets/Text/Word Wrapping"); if (ImGui::TreeNode("Word Wrapping")) { @@ -3734,13 +3815,13 @@ static void DemoWindowWidgetsTextInput() } }; - static char buf1[32] = ""; ImGui::InputText("default", buf1, 32); - static char buf2[32] = ""; ImGui::InputText("decimal", buf2, 32, ImGuiInputTextFlags_CharsDecimal); - static char buf3[32] = ""; ImGui::InputText("hexadecimal", buf3, 32, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); - static char buf4[32] = ""; ImGui::InputText("uppercase", buf4, 32, ImGuiInputTextFlags_CharsUppercase); - static char buf5[32] = ""; ImGui::InputText("no blank", buf5, 32, ImGuiInputTextFlags_CharsNoBlank); - static char buf6[32] = ""; ImGui::InputText("casing swap", buf6, 32, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterCasingSwap); // Use CharFilter callback to replace characters. - static char buf7[32] = ""; ImGui::InputText("\"imgui\"", buf7, 32, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); // Use CharFilter callback to disable some characters. + static char buf1[32] = ""; ImGui::InputText("default", buf1, IM_ARRAYSIZE(buf1)); + static char buf2[32] = ""; ImGui::InputText("decimal", buf2, IM_ARRAYSIZE(buf2), ImGuiInputTextFlags_CharsDecimal); + static char buf3[32] = ""; ImGui::InputText("hexadecimal", buf3, IM_ARRAYSIZE(buf3), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); + static char buf4[32] = ""; ImGui::InputText("uppercase", buf4, IM_ARRAYSIZE(buf4), ImGuiInputTextFlags_CharsUppercase); + static char buf5[32] = ""; ImGui::InputText("no blank", buf5, IM_ARRAYSIZE(buf5), ImGuiInputTextFlags_CharsNoBlank); + static char buf6[32] = ""; ImGui::InputText("casing swap", buf6, IM_ARRAYSIZE(buf6), ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterCasingSwap); // Use CharFilter callback to replace characters. + static char buf7[32] = ""; ImGui::InputText("\"imgui\"", buf7, IM_ARRAYSIZE(buf7), ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); // Use CharFilter callback to disable some characters. ImGui::TreePop(); } @@ -3796,20 +3877,20 @@ static void DemoWindowWidgetsTextInput() } }; static char buf1[64]; - ImGui::InputText("Completion", buf1, 64, ImGuiInputTextFlags_CallbackCompletion, Funcs::MyCallback); + ImGui::InputText("Completion", buf1, IM_ARRAYSIZE(buf1), ImGuiInputTextFlags_CallbackCompletion, Funcs::MyCallback); ImGui::SameLine(); HelpMarker( "Here we append \"..\" each time Tab is pressed. " "See 'Examples>Console' for a more meaningful demonstration of using this callback."); static char buf2[64]; - ImGui::InputText("History", buf2, 64, ImGuiInputTextFlags_CallbackHistory, Funcs::MyCallback); + ImGui::InputText("History", buf2, IM_ARRAYSIZE(buf2), ImGuiInputTextFlags_CallbackHistory, Funcs::MyCallback); ImGui::SameLine(); HelpMarker( "Here we replace and select text each time Up/Down are pressed. " "See 'Examples>Console' for a more meaningful demonstration of using this callback."); static char buf3[64]; static int edit_count = 0; - ImGui::InputText("Edit", buf3, 64, ImGuiInputTextFlags_CallbackEdit, Funcs::MyCallback, (void*)&edit_count); + ImGui::InputText("Edit", buf3, IM_ARRAYSIZE(buf3), ImGuiInputTextFlags_CallbackEdit, Funcs::MyCallback, (void*)&edit_count); ImGui::SameLine(); HelpMarker( "Here we toggle the casing of the first character on every edit + count edits."); ImGui::SameLine(); ImGui::Text("(%d)", edit_count); @@ -3995,6 +4076,7 @@ static void DemoWindowWidgetsTreeNodes() IMGUI_DEMO_MARKER("Widgets/Tree Nodes"); if (ImGui::TreeNode("Tree Nodes")) { + // See see "Examples -> Property Editor" (ShowExampleAppPropertyEditor() function) for a fancier, data-driven tree. IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Basic trees"); if (ImGui::TreeNode("Basic trees")) { @@ -4021,6 +4103,35 @@ static void DemoWindowWidgetsTreeNodes() ImGui::TreePop(); } + IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Hierarchy lines"); + if (ImGui::TreeNode("Hierarchy lines")) + { + static ImGuiTreeNodeFlags base_flags = ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DefaultOpen; + HelpMarker("Default option for DrawLinesXXX is stored in style.TreeLinesFlags"); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesNone", &base_flags, ImGuiTreeNodeFlags_DrawLinesNone); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesFull", &base_flags, ImGuiTreeNodeFlags_DrawLinesFull); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesToNodes", &base_flags, ImGuiTreeNodeFlags_DrawLinesToNodes); + + if (ImGui::TreeNodeEx("Parent", base_flags)) + { + if (ImGui::TreeNodeEx("Child 1", base_flags)) + { + ImGui::Button("Button for Child 1"); + ImGui::TreePop(); + } + if (ImGui::TreeNodeEx("Child 2", base_flags)) + { + ImGui::Button("Button for Child 2"); + ImGui::TreePop(); + } + ImGui::Text("Remaining contents"); + ImGui::Text("Remaining contents"); + ImGui::TreePop(); + } + + ImGui::TreePop(); + } + IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Advanced, with Selectable nodes"); if (ImGui::TreeNode("Advanced, with Selectable nodes")) { @@ -4038,7 +4149,13 @@ static void DemoWindowWidgetsTreeNodes() ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &base_flags, ImGuiTreeNodeFlags_SpanAllColumns); ImGui::SameLine(); HelpMarker("For use in Tables only."); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_AllowOverlap", &base_flags, ImGuiTreeNodeFlags_AllowOverlap); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_Framed", &base_flags, ImGuiTreeNodeFlags_Framed); ImGui::SameLine(); HelpMarker("Draw frame with background (e.g. for CollapsingHeader)"); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_NavLeftJumpsBackHere", &base_flags, ImGuiTreeNodeFlags_NavLeftJumpsBackHere); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_NavLeftJumpsToParent", &base_flags, ImGuiTreeNodeFlags_NavLeftJumpsToParent); + + HelpMarker("Default option for DrawLinesXXX is stored in style.TreeLinesFlags"); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesNone", &base_flags, ImGuiTreeNodeFlags_DrawLinesNone); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesFull", &base_flags, ImGuiTreeNodeFlags_DrawLinesFull); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesToNodes", &base_flags, ImGuiTreeNodeFlags_DrawLinesToNodes); + ImGui::Checkbox("Align label with current X position", &align_label_with_current_x_position); ImGui::Checkbox("Test tree node as drag source", &test_drag_and_drop); ImGui::Text("Hello!"); @@ -4221,6 +4338,7 @@ static void DemoWindowWidgets(ImGuiDemoWindowData* demo_data) DemoWindowWidgetsDragAndDrop(); DemoWindowWidgetsDragsAndSliders(); + DemoWindowWidgetsFonts(); DemoWindowWidgetsImages(); DemoWindowWidgetsListBoxes(); DemoWindowWidgetsMultiComponents(); @@ -4445,16 +4563,27 @@ static void DemoWindowLayout() } ImGui::PopItemWidth(); + ImGui::Text("SetNextItemWidth/PushItemWidth(-Min(GetContentRegionAvail().x * 0.40f, GetFontSize() * 12))"); + ImGui::PushItemWidth(-IM_MIN(ImGui::GetFontSize() * 12, ImGui::GetContentRegionAvail().x * 0.40f)); + ImGui::DragFloat("float##5a", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##5b", &f); + ImGui::Unindent(); + } + ImGui::PopItemWidth(); + // Demonstrate using PushItemWidth to surround three items. // Calling SetNextItemWidth() before each of them would have the same effect. ImGui::Text("SetNextItemWidth/PushItemWidth(-FLT_MIN)"); ImGui::SameLine(); HelpMarker("Align to right edge"); ImGui::PushItemWidth(-FLT_MIN); - ImGui::DragFloat("##float5a", &f); + ImGui::DragFloat("##float6a", &f); if (show_indented_items) { ImGui::Indent(); - ImGui::DragFloat("float (indented)##5b", &f); + ImGui::DragFloat("float (indented)##6b", &f); ImGui::Unindent(); } ImGui::PopItemWidth(); @@ -4682,10 +4811,11 @@ static void DemoWindowLayout() ImGui::SmallButton("SmallButton()"); // Tree + // (here the node appears after a button and has odd intent, so we use ImGuiTreeNodeFlags_DrawLinesNone to disable hierarchy outline) const float spacing = ImGui::GetStyle().ItemInnerSpacing.x; ImGui::Button("Button##1"); ImGui::SameLine(0.0f, spacing); - if (ImGui::TreeNode("Node##1")) + if (ImGui::TreeNodeEx("Node##1", ImGuiTreeNodeFlags_DrawLinesNone)) { // Placeholder tree data for (int i = 0; i < 6; i++) @@ -5474,7 +5604,7 @@ struct MyItem return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? -1 : +1; } - // qsort() is instable so always return a way to differenciate items. + // qsort() is instable so always return a way to differentiate items. // Your own compare function may want to avoid fallback on implicit sort specs. // e.g. a Name compare if it wasn't already part of the sort specs. return (a->ID - b->ID); @@ -6667,7 +6797,7 @@ static void DemoWindowTables() { static ImGuiTableFlags table_flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody; - static ImGuiTreeNodeFlags tree_node_flags_base = ImGuiTreeNodeFlags_SpanAllColumns; + static ImGuiTreeNodeFlags tree_node_flags_base = ImGuiTreeNodeFlags_SpanAllColumns | ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_DrawLinesFull; ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", &tree_node_flags_base, ImGuiTreeNodeFlags_SpanFullWidth); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanLabelWidth", &tree_node_flags_base, ImGuiTreeNodeFlags_SpanLabelWidth); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &tree_node_flags_base, ImGuiTreeNodeFlags_SpanAllColumns); @@ -7837,7 +7967,7 @@ static void DemoWindowInputs() ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags) ? "PRESSED" : "..."); // 2: InputText also polling for CTRL+A: it always uses _RouteFocused internally (gets priority when active) - // (Commmented because the owner-aware version of Shortcut() is still in imgui_internal.h) + // (Commented because the owner-aware version of Shortcut() is still in imgui_internal.h) //char str[16] = "Press CTRL+A"; //ImGui::Spacing(); //ImGui::InputText("InputTextB", str, IM_ARRAYSIZE(str), ImGuiInputTextFlags_ReadOnly); @@ -7864,7 +7994,7 @@ static void DemoWindowInputs() { ImGui::Text("(in PopupF)"); ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags) ? "PRESSED" : "..."); - // (Commmented because the owner-aware version of Shortcut() is still in imgui_internal.h) + // (Commented because the owner-aware version of Shortcut() is still in imgui_internal.h) //ImGui::InputText("InputTextG", str, IM_ARRAYSIZE(str), ImGuiInputTextFlags_ReadOnly); //ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags, ImGui::GetItemID()) ? "PRESSED" : "..."); ImGui::EndPopup(); @@ -8015,6 +8145,8 @@ void ImGui::ShowAboutWindow(bool* p_open) ImGui::SameLine(); ImGui::TextLinkOpenURL("Wiki", "https://github.com/ocornut/imgui/wiki"); ImGui::SameLine(); + ImGui::TextLinkOpenURL("Extensions", "https://github.com/ocornut/imgui/wiki/Useful-Extensions"); + ImGui::SameLine(); ImGui::TextLinkOpenURL("Releases", "https://github.com/ocornut/imgui/releases"); ImGui::SameLine(); ImGui::TextLinkOpenURL("Funding", "https://github.com/ocornut/imgui/wiki/Funding"); @@ -8038,7 +8170,7 @@ void ImGui::ShowAboutWindow(bool* p_open) if (copy_to_clipboard) { ImGui::LogToClipboard(); - ImGui::LogText("```\n"); // Back quotes will make text appears without formatting when pasting on GitHub + ImGui::LogText("```cpp\n"); // Back quotes will make text appears without formatting when pasting on GitHub } ImGui::Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); @@ -8129,9 +8261,9 @@ void ImGui::ShowAboutWindow(bool* p_open) if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) ImGui::Text(" NoKeyboard"); if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) ImGui::Text(" DockingEnable"); if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) ImGui::Text(" ViewportsEnable"); - if (io.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports) ImGui::Text(" DpiEnableScaleViewports"); - if (io.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ImGui::Text(" DpiEnableScaleFonts"); if (io.MouseDrawCursor) ImGui::Text("io.MouseDrawCursor"); + if (io.ConfigDpiScaleFonts) ImGui::Text("io.ConfigDpiScaleFonts"); + if (io.ConfigDpiScaleViewports) ImGui::Text("io.ConfigDpiScaleViewports"); if (io.ConfigViewportsNoAutoMerge) ImGui::Text("io.ConfigViewportsNoAutoMerge"); if (io.ConfigViewportsNoTaskBarIcon) ImGui::Text("io.ConfigViewportsNoTaskBarIcon"); if (io.ConfigViewportsNoDecoration) ImGui::Text("io.ConfigViewportsNoDecoration"); @@ -8154,9 +8286,11 @@ void ImGui::ShowAboutWindow(bool* p_open) if (io.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) ImGui::Text(" PlatformHasViewports"); if (io.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)ImGui::Text(" HasMouseHoveredViewport"); if (io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) ImGui::Text(" RendererHasVtxOffset"); + if (io.BackendFlags & ImGuiBackendFlags_RendererHasTextures) ImGui::Text(" RendererHasTextures"); if (io.BackendFlags & ImGuiBackendFlags_RendererHasViewports) ImGui::Text(" RendererHasViewports"); ImGui::Separator(); - ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexWidth, io.Fonts->TexHeight); + ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexData->Width, io.Fonts->TexData->Height); + ImGui::Text("io.Fonts->FontLoaderName: %s", io.Fonts->FontLoaderName ? io.Fonts->FontLoaderName : "NULL"); ImGui::Text("io.DisplaySize: %.2f,%.2f", io.DisplaySize.x, io.DisplaySize.y); ImGui::Text("io.DisplayFramebufferScale: %.2f,%.2f", io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y); ImGui::Separator(); @@ -8181,41 +8315,10 @@ void ImGui::ShowAboutWindow(bool* p_open) //----------------------------------------------------------------------------- // [SECTION] Style Editor / ShowStyleEditor() //----------------------------------------------------------------------------- -// - ShowFontSelector() // - ShowStyleSelector() // - ShowStyleEditor() //----------------------------------------------------------------------------- -// Forward declare ShowFontAtlas() which isn't worth putting in public API yet -namespace ImGui { IMGUI_API void ShowFontAtlas(ImFontAtlas* atlas); } - -// Demo helper function to select among loaded fonts. -// Here we use the regular BeginCombo()/EndCombo() api which is the more flexible one. -void ImGui::ShowFontSelector(const char* label) -{ - ImGuiIO& io = ImGui::GetIO(); - ImFont* font_current = ImGui::GetFont(); - if (ImGui::BeginCombo(label, font_current->GetDebugName())) - { - for (ImFont* font : io.Fonts->Fonts) - { - ImGui::PushID((void*)font); - if (ImGui::Selectable(font->GetDebugName(), font == font_current)) - io.FontDefault = font; - if (font == font_current) - ImGui::SetItemDefaultFocus(); - ImGui::PopID(); - } - ImGui::EndCombo(); - } - ImGui::SameLine(); - HelpMarker( - "- Load additional fonts with io.Fonts->AddFontFromFileTTF().\n" - "- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n" - "- Read FAQ and docs/FONTS.md for more details.\n" - "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame()."); -} - // Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options. // Here we use the simplified Combo() api that packs items into a single literal string. // Useful for quick combo boxes where the choices are known locally. @@ -8235,12 +8338,21 @@ bool ImGui::ShowStyleSelector(const char* label) return false; } +static const char* GetTreeLinesFlagsName(ImGuiTreeNodeFlags flags) +{ + if (flags == ImGuiTreeNodeFlags_DrawLinesNone) return "DrawLinesNone"; + if (flags == ImGuiTreeNodeFlags_DrawLinesFull) return "DrawLinesFull"; + if (flags == ImGuiTreeNodeFlags_DrawLinesToNodes) return "DrawLinesToNodes"; + return ""; +} + +// We omit the ImGui:: prefix in this function, as we don't expect user to be copy and pasting this code. void ImGui::ShowStyleEditor(ImGuiStyle* ref) { IMGUI_DEMO_MARKER("Tools/Style Editor"); // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to // (without a reference style pointer, we will use one compared locally as a reference) - ImGuiStyle& style = ImGui::GetStyle(); + ImGuiStyle& style = GetStyle(); static ImGuiStyle ref_saved_style; // Default to using internal storage as reference @@ -8251,197 +8363,232 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) if (ref == NULL) ref = &ref_saved_style; - ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.50f); + PushItemWidth(GetWindowWidth() * 0.50f); - if (ImGui::ShowStyleSelector("Colors##Selector")) - ref_saved_style = style; - ImGui::ShowFontSelector("Fonts##Selector"); + { + // General + SeparatorText("General"); + if ((GetIO().BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) + { + BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!"); + BulletText("For instructions, see:"); + SameLine(); + TextLinkOpenURL("docs/BACKENDS.md", "https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md"); + } - // Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f) - if (ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f")) - style.GrabRounding = style.FrameRounding; // Make GrabRounding always the same value as FrameRounding - { bool border = (style.WindowBorderSize > 0.0f); if (ImGui::Checkbox("WindowBorder", &border)) { style.WindowBorderSize = border ? 1.0f : 0.0f; } } - ImGui::SameLine(); - { bool border = (style.FrameBorderSize > 0.0f); if (ImGui::Checkbox("FrameBorder", &border)) { style.FrameBorderSize = border ? 1.0f : 0.0f; } } - ImGui::SameLine(); - { bool border = (style.PopupBorderSize > 0.0f); if (ImGui::Checkbox("PopupBorder", &border)) { style.PopupBorderSize = border ? 1.0f : 0.0f; } } + if (ShowStyleSelector("Colors##Selector")) + ref_saved_style = style; + ShowFontSelector("Fonts##Selector"); + if (DragFloat("FontSizeBase", &style.FontSizeBase, 0.20f, 5.0f, 100.0f, "%.0f")) + style._NextFrameFontSizeBase = style.FontSizeBase; // FIXME: Temporary hack until we finish remaining work. + SameLine(0.0f, 0.0f); Text(" (out %.2f)", GetFontSize()); + DragFloat("FontScaleMain", &style.FontScaleMain, 0.02f, 0.5f, 4.0f); + //BeginDisabled(GetIO().ConfigDpiScaleFonts); + DragFloat("FontScaleDpi", &style.FontScaleDpi, 0.02f, 0.5f, 4.0f); + //SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten."); + //EndDisabled(); + + // Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f) + if (SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f")) + style.GrabRounding = style.FrameRounding; // Make GrabRounding always the same value as FrameRounding + { bool border = (style.WindowBorderSize > 0.0f); if (Checkbox("WindowBorder", &border)) { style.WindowBorderSize = border ? 1.0f : 0.0f; } } + SameLine(); + { bool border = (style.FrameBorderSize > 0.0f); if (Checkbox("FrameBorder", &border)) { style.FrameBorderSize = border ? 1.0f : 0.0f; } } + SameLine(); + { bool border = (style.PopupBorderSize > 0.0f); if (Checkbox("PopupBorder", &border)) { style.PopupBorderSize = border ? 1.0f : 0.0f; } } + } // Save/Revert button - if (ImGui::Button("Save Ref")) + if (Button("Save Ref")) *ref = ref_saved_style = style; - ImGui::SameLine(); - if (ImGui::Button("Revert Ref")) + SameLine(); + if (Button("Revert Ref")) style = *ref; - ImGui::SameLine(); + SameLine(); HelpMarker( "Save/Revert in local non-persistent storage. Default Colors definition are not affected. " "Use \"Export\" below to save them somewhere."); - ImGui::Separator(); - - if (ImGui::BeginTabBar("##tabs", ImGuiTabBarFlags_None)) + SeparatorText("Details"); + if (BeginTabBar("##tabs", ImGuiTabBarFlags_None)) { - if (ImGui::BeginTabItem("Sizes")) + if (BeginTabItem("Sizes")) { - ImGui::SeparatorText("Main"); - ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f"); - ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f"); - ImGui::SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f"); - ImGui::SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f"); + SeparatorText("Main"); + SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f"); + SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); + SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); + SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); + SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f"); + SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f"); + SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f"); + SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f"); - ImGui::SeparatorText("Borders"); - ImGui::SliderFloat("WindowBorderSize", &style.WindowBorderSize, 0.0f, 1.0f, "%.0f"); - ImGui::SliderFloat("ChildBorderSize", &style.ChildBorderSize, 0.0f, 1.0f, "%.0f"); - ImGui::SliderFloat("PopupBorderSize", &style.PopupBorderSize, 0.0f, 1.0f, "%.0f"); - ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f"); + SeparatorText("Borders"); + SliderFloat("WindowBorderSize", &style.WindowBorderSize, 0.0f, 1.0f, "%.0f"); + SliderFloat("ChildBorderSize", &style.ChildBorderSize, 0.0f, 1.0f, "%.0f"); + SliderFloat("PopupBorderSize", &style.PopupBorderSize, 0.0f, 1.0f, "%.0f"); + SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f"); - ImGui::SeparatorText("Rounding"); - ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 12.0f, "%.0f"); - ImGui::SliderFloat("ChildRounding", &style.ChildRounding, 0.0f, 12.0f, "%.0f"); - ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f"); - ImGui::SliderFloat("PopupRounding", &style.PopupRounding, 0.0f, 12.0f, "%.0f"); - ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 12.0f, "%.0f"); - ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 12.0f, "%.0f"); + SeparatorText("Rounding"); + SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("ChildRounding", &style.ChildRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("PopupRounding", &style.PopupRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 12.0f, "%.0f"); + SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 12.0f, "%.0f"); - ImGui::SeparatorText("Tabs"); - ImGui::SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f"); - ImGui::SliderFloat("TabBarBorderSize", &style.TabBarBorderSize, 0.0f, 2.0f, "%.0f"); - ImGui::SliderFloat("TabBarOverlineSize", &style.TabBarOverlineSize, 0.0f, 3.0f, "%.0f"); - ImGui::SameLine(); HelpMarker("Overline is only drawn over the selected tab when ImGuiTabBarFlags_DrawSelectedOverline is set."); - ImGui::DragFloat("TabCloseButtonMinWidthSelected", &style.TabCloseButtonMinWidthSelected, 0.1f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthSelected < 0.0f) ? "%.0f (Always)" : "%.0f"); - ImGui::DragFloat("TabCloseButtonMinWidthUnselected", &style.TabCloseButtonMinWidthUnselected, 0.1f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthUnselected < 0.0f) ? "%.0f (Always)" : "%.0f"); - ImGui::SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f"); + SeparatorText("Tabs"); + SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f"); + SliderFloat("TabBarBorderSize", &style.TabBarBorderSize, 0.0f, 2.0f, "%.0f"); + SliderFloat("TabBarOverlineSize", &style.TabBarOverlineSize, 0.0f, 3.0f, "%.0f"); + SameLine(); HelpMarker("Overline is only drawn over the selected tab when ImGuiTabBarFlags_DrawSelectedOverline is set."); + DragFloat("TabCloseButtonMinWidthSelected", &style.TabCloseButtonMinWidthSelected, 0.1f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthSelected < 0.0f) ? "%.0f (Always)" : "%.0f"); + DragFloat("TabCloseButtonMinWidthUnselected", &style.TabCloseButtonMinWidthUnselected, 0.1f, -1.0f, 100.0f, (style.TabCloseButtonMinWidthUnselected < 0.0f) ? "%.0f (Always)" : "%.0f"); + SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f"); - ImGui::SeparatorText("Tables"); - ImGui::SliderFloat2("CellPadding", (float*)&style.CellPadding, 0.0f, 20.0f, "%.0f"); - ImGui::SliderAngle("TableAngledHeadersAngle", &style.TableAngledHeadersAngle, -50.0f, +50.0f); - ImGui::SliderFloat2("TableAngledHeadersTextAlign", (float*)&style.TableAngledHeadersTextAlign, 0.0f, 1.0f, "%.2f"); + SeparatorText("Tables"); + SliderFloat2("CellPadding", (float*)&style.CellPadding, 0.0f, 20.0f, "%.0f"); + SliderAngle("TableAngledHeadersAngle", &style.TableAngledHeadersAngle, -50.0f, +50.0f); + SliderFloat2("TableAngledHeadersTextAlign", (float*)&style.TableAngledHeadersTextAlign, 0.0f, 1.0f, "%.2f"); - ImGui::SeparatorText("Windows"); - ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); - ImGui::SliderFloat("WindowBorderHoverPadding", &style.WindowBorderHoverPadding, 1.0f, 20.0f, "%.0f"); + SeparatorText("Trees"); + bool combo_open = BeginCombo("TreeLinesFlags", GetTreeLinesFlagsName(style.TreeLinesFlags)); + SameLine(); + HelpMarker("[Experimental] Tree lines may not work in all situations (e.g. using a clipper) and may incurs slight traversal overhead.\n\nImGuiTreeNodeFlags_DrawLinesFull is faster than ImGuiTreeNodeFlags_DrawLinesToNode."); + if (combo_open) + { + const ImGuiTreeNodeFlags options[] = { ImGuiTreeNodeFlags_DrawLinesNone, ImGuiTreeNodeFlags_DrawLinesFull, ImGuiTreeNodeFlags_DrawLinesToNodes }; + for (ImGuiTreeNodeFlags option : options) + if (Selectable(GetTreeLinesFlagsName(option), style.TreeLinesFlags == option)) + style.TreeLinesFlags = option; + EndCombo(); + } + SliderFloat("TreeLinesSize", &style.TreeLinesSize, 0.0f, 2.0f, "%.0f"); + SliderFloat("TreeLinesRounding", &style.TreeLinesRounding, 0.0f, 12.0f, "%.0f"); + + SeparatorText("Windows"); + SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); + SliderFloat("WindowBorderHoverPadding", &style.WindowBorderHoverPadding, 1.0f, 20.0f, "%.0f"); int window_menu_button_position = style.WindowMenuButtonPosition + 1; - if (ImGui::Combo("WindowMenuButtonPosition", (int*)&window_menu_button_position, "None\0Left\0Right\0")) + if (Combo("WindowMenuButtonPosition", (int*)&window_menu_button_position, "None\0Left\0Right\0")) style.WindowMenuButtonPosition = (ImGuiDir)(window_menu_button_position - 1); - ImGui::SeparatorText("Widgets"); - ImGui::Combo("ColorButtonPosition", (int*)&style.ColorButtonPosition, "Left\0Right\0"); - ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); - ImGui::SameLine(); HelpMarker("Alignment applies when a button is larger than its text content."); - ImGui::SliderFloat2("SelectableTextAlign", (float*)&style.SelectableTextAlign, 0.0f, 1.0f, "%.2f"); - ImGui::SameLine(); HelpMarker("Alignment applies when a selectable is larger than its text content."); - ImGui::SliderFloat("SeparatorTextBorderSize", &style.SeparatorTextBorderSize, 0.0f, 10.0f, "%.0f"); - ImGui::SliderFloat2("SeparatorTextAlign", (float*)&style.SeparatorTextAlign, 0.0f, 1.0f, "%.2f"); - ImGui::SliderFloat2("SeparatorTextPadding", (float*)&style.SeparatorTextPadding, 0.0f, 40.0f, "%.0f"); - ImGui::SliderFloat("LogSliderDeadzone", &style.LogSliderDeadzone, 0.0f, 12.0f, "%.0f"); - ImGui::SliderFloat("ImageBorderSize", &style.ImageBorderSize, 0.0f, 1.0f, "%.0f"); + SeparatorText("Widgets"); + Combo("ColorButtonPosition", (int*)&style.ColorButtonPosition, "Left\0Right\0"); + SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); + SameLine(); HelpMarker("Alignment applies when a button is larger than its text content."); + SliderFloat2("SelectableTextAlign", (float*)&style.SelectableTextAlign, 0.0f, 1.0f, "%.2f"); + SameLine(); HelpMarker("Alignment applies when a selectable is larger than its text content."); + SliderFloat("SeparatorTextBorderSize", &style.SeparatorTextBorderSize, 0.0f, 10.0f, "%.0f"); + SliderFloat2("SeparatorTextAlign", (float*)&style.SeparatorTextAlign, 0.0f, 1.0f, "%.2f"); + SliderFloat2("SeparatorTextPadding", (float*)&style.SeparatorTextPadding, 0.0f, 40.0f, "%.0f"); + SliderFloat("LogSliderDeadzone", &style.LogSliderDeadzone, 0.0f, 12.0f, "%.0f"); + SliderFloat("ImageBorderSize", &style.ImageBorderSize, 0.0f, 1.0f, "%.0f"); - ImGui::SeparatorText("Docking"); - ImGui::SliderFloat("DockingSplitterSize", &style.DockingSeparatorSize, 0.0f, 12.0f, "%.0f"); + SeparatorText("Docking"); + SliderFloat("DockingSeparatorSize", &style.DockingSeparatorSize, 0.0f, 12.0f, "%.0f"); - ImGui::SeparatorText("Tooltips"); + SeparatorText("Tooltips"); for (int n = 0; n < 2; n++) - if (ImGui::TreeNodeEx(n == 0 ? "HoverFlagsForTooltipMouse" : "HoverFlagsForTooltipNav")) + if (TreeNodeEx(n == 0 ? "HoverFlagsForTooltipMouse" : "HoverFlagsForTooltipNav")) { ImGuiHoveredFlags* p = (n == 0) ? &style.HoverFlagsForTooltipMouse : &style.HoverFlagsForTooltipNav; - ImGui::CheckboxFlags("ImGuiHoveredFlags_DelayNone", p, ImGuiHoveredFlags_DelayNone); - ImGui::CheckboxFlags("ImGuiHoveredFlags_DelayShort", p, ImGuiHoveredFlags_DelayShort); - ImGui::CheckboxFlags("ImGuiHoveredFlags_DelayNormal", p, ImGuiHoveredFlags_DelayNormal); - ImGui::CheckboxFlags("ImGuiHoveredFlags_Stationary", p, ImGuiHoveredFlags_Stationary); - ImGui::CheckboxFlags("ImGuiHoveredFlags_NoSharedDelay", p, ImGuiHoveredFlags_NoSharedDelay); - ImGui::TreePop(); + CheckboxFlags("ImGuiHoveredFlags_DelayNone", p, ImGuiHoveredFlags_DelayNone); + CheckboxFlags("ImGuiHoveredFlags_DelayShort", p, ImGuiHoveredFlags_DelayShort); + CheckboxFlags("ImGuiHoveredFlags_DelayNormal", p, ImGuiHoveredFlags_DelayNormal); + CheckboxFlags("ImGuiHoveredFlags_Stationary", p, ImGuiHoveredFlags_Stationary); + CheckboxFlags("ImGuiHoveredFlags_NoSharedDelay", p, ImGuiHoveredFlags_NoSharedDelay); + TreePop(); } - ImGui::SeparatorText("Misc"); - ImGui::SliderFloat2("DisplayWindowPadding", (float*)&style.DisplayWindowPadding, 0.0f, 30.0f, "%.0f"); ImGui::SameLine(); HelpMarker("Apply to regular windows: amount which we enforce to keep visible when moving near edges of your screen."); - ImGui::SliderFloat2("DisplaySafeAreaPadding", (float*)&style.DisplaySafeAreaPadding, 0.0f, 30.0f, "%.0f"); ImGui::SameLine(); HelpMarker("Apply to every windows, menus, popups, tooltips: amount where we avoid displaying contents. Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured)."); + SeparatorText("Misc"); + SliderFloat2("DisplayWindowPadding", (float*)&style.DisplayWindowPadding, 0.0f, 30.0f, "%.0f"); SameLine(); HelpMarker("Apply to regular windows: amount which we enforce to keep visible when moving near edges of your screen."); + SliderFloat2("DisplaySafeAreaPadding", (float*)&style.DisplaySafeAreaPadding, 0.0f, 30.0f, "%.0f"); SameLine(); HelpMarker("Apply to every windows, menus, popups, tooltips: amount where we avoid displaying contents. Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured)."); - ImGui::EndTabItem(); + EndTabItem(); } - if (ImGui::BeginTabItem("Colors")) + if (BeginTabItem("Colors")) { static int output_dest = 0; static bool output_only_modified = true; - if (ImGui::Button("Export")) + if (Button("Export")) { if (output_dest == 0) - ImGui::LogToClipboard(); + LogToClipboard(); else - ImGui::LogToTTY(); - ImGui::LogText("ImVec4* colors = ImGui::GetStyle().Colors;" IM_NEWLINE); + LogToTTY(); + LogText("ImVec4* colors = GetStyle().Colors;" IM_NEWLINE); for (int i = 0; i < ImGuiCol_COUNT; i++) { const ImVec4& col = style.Colors[i]; - const char* name = ImGui::GetStyleColorName(i); + const char* name = GetStyleColorName(i); if (!output_only_modified || memcmp(&col, &ref->Colors[i], sizeof(ImVec4)) != 0) - ImGui::LogText("colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, + LogText("colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, name, 23 - (int)strlen(name), "", col.x, col.y, col.z, col.w); } - ImGui::LogFinish(); + LogFinish(); } - ImGui::SameLine(); ImGui::SetNextItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); - ImGui::SameLine(); ImGui::Checkbox("Only Modified Colors", &output_only_modified); + SameLine(); SetNextItemWidth(120); Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); + SameLine(); Checkbox("Only Modified Colors", &output_only_modified); static ImGuiTextFilter filter; - filter.Draw("Filter colors", ImGui::GetFontSize() * 16); + filter.Draw("Filter colors", GetFontSize() * 16); static ImGuiColorEditFlags alpha_flags = 0; - if (ImGui::RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_AlphaOpaque)) { alpha_flags = ImGuiColorEditFlags_AlphaOpaque; } ImGui::SameLine(); - if (ImGui::RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_None)) { alpha_flags = ImGuiColorEditFlags_None; } ImGui::SameLine(); - if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } ImGui::SameLine(); + if (RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_AlphaOpaque)) { alpha_flags = ImGuiColorEditFlags_AlphaOpaque; } SameLine(); + if (RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_None)) { alpha_flags = ImGuiColorEditFlags_None; } SameLine(); + if (RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } SameLine(); HelpMarker( "In the color list:\n" "Left-click on color square to open color picker,\n" "Right-click to open edit options menu."); - ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, ImGui::GetTextLineHeightWithSpacing() * 10), ImVec2(FLT_MAX, FLT_MAX)); - ImGui::BeginChild("##colors", ImVec2(0, 0), ImGuiChildFlags_Borders | ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar); - ImGui::PushItemWidth(ImGui::GetFontSize() * -12); + SetNextWindowSizeConstraints(ImVec2(0.0f, GetTextLineHeightWithSpacing() * 10), ImVec2(FLT_MAX, FLT_MAX)); + BeginChild("##colors", ImVec2(0, 0), ImGuiChildFlags_Borders | ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar); + PushItemWidth(GetFontSize() * -12); for (int i = 0; i < ImGuiCol_COUNT; i++) { - const char* name = ImGui::GetStyleColorName(i); + const char* name = GetStyleColorName(i); if (!filter.PassFilter(name)) continue; - ImGui::PushID(i); + PushID(i); #ifndef IMGUI_DISABLE_DEBUG_TOOLS - if (ImGui::Button("?")) - ImGui::DebugFlashStyleColor((ImGuiCol)i); - ImGui::SetItemTooltip("Flash given color to identify places where it is used."); - ImGui::SameLine(); + if (Button("?")) + DebugFlashStyleColor((ImGuiCol)i); + SetItemTooltip("Flash given color to identify places where it is used."); + SameLine(); #endif - ImGui::ColorEdit4("##color", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags); + ColorEdit4("##color", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags); if (memcmp(&style.Colors[i], &ref->Colors[i], sizeof(ImVec4)) != 0) { // Tips: in a real user application, you may want to merge and use an icon font into the main font, // so instead of "Save"/"Revert" you'd use icons! // Read the FAQ and docs/FONTS.md about using icon fonts. It's really easy and super convenient! - ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Save")) { ref->Colors[i] = style.Colors[i]; } - ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Revert")) { style.Colors[i] = ref->Colors[i]; } + SameLine(0.0f, style.ItemInnerSpacing.x); if (Button("Save")) { ref->Colors[i] = style.Colors[i]; } + SameLine(0.0f, style.ItemInnerSpacing.x); if (Button("Revert")) { style.Colors[i] = ref->Colors[i]; } } - ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); - ImGui::TextUnformatted(name); - ImGui::PopID(); + SameLine(0.0f, style.ItemInnerSpacing.x); + TextUnformatted(name); + PopID(); } - ImGui::PopItemWidth(); - ImGui::EndChild(); + PopItemWidth(); + EndChild(); - ImGui::EndTabItem(); + EndTabItem(); } - if (ImGui::BeginTabItem("Fonts")) + if (BeginTabItem("Fonts")) { - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = GetIO(); ImFontAtlas* atlas = io.Fonts; - HelpMarker("Read FAQ and docs/FONTS.md for details on font loading."); - ImGui::ShowFontAtlas(atlas); + ShowFontAtlas(atlas); // Post-baking font scaling. Note that this is NOT the nice way of scaling fonts, read below. // (we enforce hard clamping manually as by default DragFloat/SliderFloat allows CTRL+Click text to get out of bounds). + /* + SeparatorText("Legacy Scaling"); const float MIN_SCALE = 0.3f; const float MAX_SCALE = 2.0f; HelpMarker( @@ -8449,136 +8596,137 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) "However, the _correct_ way of scaling your UI is currently to reload your font at the designed size, " "rebuild the font atlas, and call style.ScaleAllSizes() on a reference ImGuiStyle structure.\n" "Using those settings here will give you poor quality results."); - static float window_scale = 1.0f; - ImGui::PushItemWidth(ImGui::GetFontSize() * 8); - if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp)) // Scale only this window - ImGui::SetWindowFontScale(window_scale); - ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp); // Scale everything - ImGui::PopItemWidth(); + PushItemWidth(GetFontSize() * 8); + DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp); // Scale everything + //static float window_scale = 1.0f; + //if (DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp)) // Scale only this window + // SetWindowFontScale(window_scale); + PopItemWidth(); + */ - ImGui::EndTabItem(); + EndTabItem(); } - if (ImGui::BeginTabItem("Rendering")) + if (BeginTabItem("Rendering")) { - ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); - ImGui::SameLine(); + Checkbox("Anti-aliased lines", &style.AntiAliasedLines); + SameLine(); HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well."); - ImGui::Checkbox("Anti-aliased lines use texture", &style.AntiAliasedLinesUseTex); - ImGui::SameLine(); + Checkbox("Anti-aliased lines use texture", &style.AntiAliasedLinesUseTex); + SameLine(); HelpMarker("Faster lines using texture data. Require backend to render with bilinear filtering (not point/nearest filtering)."); - ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill); - ImGui::PushItemWidth(ImGui::GetFontSize() * 8); - ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f"); + Checkbox("Anti-aliased fill", &style.AntiAliasedFill); + PushItemWidth(GetFontSize() * 8); + DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f"); if (style.CurveTessellationTol < 0.10f) style.CurveTessellationTol = 0.10f; // When editing the "Circle Segment Max Error" value, draw a preview of its effect on auto-tessellated circles. - ImGui::DragFloat("Circle Tessellation Max Error", &style.CircleTessellationMaxError , 0.005f, 0.10f, 5.0f, "%.2f", ImGuiSliderFlags_AlwaysClamp); - const bool show_samples = ImGui::IsItemActive(); + DragFloat("Circle Tessellation Max Error", &style.CircleTessellationMaxError , 0.005f, 0.10f, 5.0f, "%.2f", ImGuiSliderFlags_AlwaysClamp); + const bool show_samples = IsItemActive(); if (show_samples) - ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos()); - if (show_samples && ImGui::BeginTooltip()) + SetNextWindowPos(GetCursorScreenPos()); + if (show_samples && BeginTooltip()) { - ImGui::TextUnformatted("(R = radius, N = approx number of segments)"); - ImGui::Spacing(); - ImDrawList* draw_list = ImGui::GetWindowDrawList(); - const float min_widget_width = ImGui::CalcTextSize("R: MMM\nN: MMM").x; + TextUnformatted("(R = radius, N = approx number of segments)"); + Spacing(); + ImDrawList* draw_list = GetWindowDrawList(); + const float min_widget_width = CalcTextSize("R: MMM\nN: MMM").x; for (int n = 0; n < 8; n++) { const float RAD_MIN = 5.0f; const float RAD_MAX = 70.0f; const float rad = RAD_MIN + (RAD_MAX - RAD_MIN) * (float)n / (8.0f - 1.0f); - ImGui::BeginGroup(); + BeginGroup(); // N is not always exact here due to how PathArcTo() function work internally - ImGui::Text("R: %.f\nN: %d", rad, draw_list->_CalcCircleAutoSegmentCount(rad)); + Text("R: %.f\nN: %d", rad, draw_list->_CalcCircleAutoSegmentCount(rad)); const float canvas_width = IM_MAX(min_widget_width, rad * 2.0f); const float offset_x = floorf(canvas_width * 0.5f); const float offset_y = floorf(RAD_MAX); - const ImVec2 p1 = ImGui::GetCursorScreenPos(); - draw_list->AddCircle(ImVec2(p1.x + offset_x, p1.y + offset_y), rad, ImGui::GetColorU32(ImGuiCol_Text)); - ImGui::Dummy(ImVec2(canvas_width, RAD_MAX * 2)); + const ImVec2 p1 = GetCursorScreenPos(); + draw_list->AddCircle(ImVec2(p1.x + offset_x, p1.y + offset_y), rad, GetColorU32(ImGuiCol_Text)); + Dummy(ImVec2(canvas_width, RAD_MAX * 2)); /* - const ImVec2 p2 = ImGui::GetCursorScreenPos(); - draw_list->AddCircleFilled(ImVec2(p2.x + offset_x, p2.y + offset_y), rad, ImGui::GetColorU32(ImGuiCol_Text)); - ImGui::Dummy(ImVec2(canvas_width, RAD_MAX * 2)); + const ImVec2 p2 = GetCursorScreenPos(); + draw_list->AddCircleFilled(ImVec2(p2.x + offset_x, p2.y + offset_y), rad, GetColorU32(ImGuiCol_Text)); + Dummy(ImVec2(canvas_width, RAD_MAX * 2)); */ - ImGui::EndGroup(); - ImGui::SameLine(); + EndGroup(); + SameLine(); } - ImGui::EndTooltip(); + EndTooltip(); } - ImGui::SameLine(); + SameLine(); HelpMarker("When drawing circle primitives with \"num_segments == 0\" tessellation will be calculated automatically."); - ImGui::DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero. - ImGui::DragFloat("Disabled Alpha", &style.DisabledAlpha, 0.005f, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Additional alpha multiplier for disabled items (multiply over current value of Alpha)."); - ImGui::PopItemWidth(); + DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero. + DragFloat("Disabled Alpha", &style.DisabledAlpha, 0.005f, 0.0f, 1.0f, "%.2f"); SameLine(); HelpMarker("Additional alpha multiplier for disabled items (multiply over current value of Alpha)."); + PopItemWidth(); - ImGui::EndTabItem(); + EndTabItem(); } - if (ImGui::BeginTabItem("Shadows")) + if (BeginTabItem("Shadows")) { - ImGui::Text("Window shadows:"); - ImGui::ColorEdit4("Color", (float*)&style.Colors[ImGuiCol_WindowShadow], ImGuiColorEditFlags_AlphaBar); - ImGui::SameLine(); + Text("Window shadows:"); + ColorEdit4("Color", (float*)&style.Colors[ImGuiCol_WindowShadow], ImGuiColorEditFlags_AlphaBar); + SameLine(); HelpMarker("Same as 'WindowShadow' in Colors tab."); - ImGui::SliderFloat("Size", &style.WindowShadowSize, 0.0f, 128.0f, "%.1f"); - ImGui::SameLine(); + SliderFloat("Size", &style.WindowShadowSize, 0.0f, 128.0f, "%.1f"); + SameLine(); HelpMarker("Set shadow size to zero to disable shadows."); - ImGui::SliderFloat("Offset distance", &style.WindowShadowOffsetDist, 0.0f, 64.0f, "%.0f"); - ImGui::SliderAngle("Offset angle", &style.WindowShadowOffsetAngle); + SliderFloat("Offset distance", &style.WindowShadowOffsetDist, 0.0f, 64.0f, "%.0f"); + SliderAngle("Offset angle", &style.WindowShadowOffsetAngle); - ImGui::EndTabItem(); + EndTabItem(); } - ImGui::EndTabBar(); + EndTabBar(); } - - ImGui::PopItemWidth(); + PopItemWidth(); } //----------------------------------------------------------------------------- // [SECTION] User Guide / ShowUserGuide() //----------------------------------------------------------------------------- +// We omit the ImGui:: prefix in this function, as we don't expect user to be copy and pasting this code. void ImGui::ShowUserGuide() { - ImGuiIO& io = ImGui::GetIO(); - ImGui::BulletText("Double-click on title bar to collapse window."); - ImGui::BulletText( + ImGuiIO& io = GetIO(); + BulletText("Double-click on title bar to collapse window."); + BulletText( "Click and drag on lower corner to resize window\n" "(double-click to auto fit window to its contents)."); - ImGui::BulletText("CTRL+Click on a slider or drag box to input value as text."); - ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); - ImGui::BulletText("CTRL+Tab to select a window."); + BulletText("CTRL+Click on a slider or drag box to input value as text."); + BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); + BulletText("CTRL+Tab to select a window."); if (io.FontAllowUserScaling) - ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents."); - ImGui::BulletText("While inputting text:\n"); - ImGui::Indent(); - ImGui::BulletText("CTRL+Left/Right to word jump."); - ImGui::BulletText("CTRL+A or double-click to select all."); - ImGui::BulletText("CTRL+X/C/V to use clipboard cut/copy/paste."); - ImGui::BulletText("CTRL+Z to undo, CTRL+Y/CTRL+SHIFT+Z to redo."); - ImGui::BulletText("ESCAPE to revert."); - ImGui::Unindent(); - ImGui::BulletText("With keyboard navigation enabled:"); - ImGui::Indent(); - ImGui::BulletText("Arrow keys to navigate."); - ImGui::BulletText("Space to activate a widget."); - ImGui::BulletText("Return to input text into a widget."); - ImGui::BulletText("Escape to deactivate a widget, close popup, exit child window."); - ImGui::BulletText("Alt to jump to the menu layer of a window."); - ImGui::Unindent(); + BulletText("CTRL+Mouse Wheel to zoom window contents."); + BulletText("While inputting text:\n"); + Indent(); + BulletText("CTRL+Left/Right to word jump."); + BulletText("CTRL+A or double-click to select all."); + BulletText("CTRL+X/C/V to use clipboard cut/copy/paste."); + BulletText("CTRL+Z to undo, CTRL+Y/CTRL+SHIFT+Z to redo."); + BulletText("ESCAPE to revert."); + Unindent(); + BulletText("With keyboard navigation enabled:"); + Indent(); + BulletText("Arrow keys to navigate."); + BulletText("Space to activate a widget."); + BulletText("Return to input text into a widget."); + BulletText("Escape to deactivate a widget, close popup, exit child window."); + BulletText("Alt to jump to the menu layer of a window."); + Unindent(); } //----------------------------------------------------------------------------- @@ -9400,8 +9548,10 @@ struct ExampleAppPropertyEditor ImGui::TableNextColumn(); ImGui::PushID(node->UID); ImGuiTreeNodeFlags tree_flags = ImGuiTreeNodeFlags_None; - tree_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; // Standard opening mode as we are likely to want to add selection afterwards - tree_flags |= ImGuiTreeNodeFlags_NavLeftJumpsBackHere; // Left arrow support + tree_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick;// Standard opening mode as we are likely to want to add selection afterwards + tree_flags |= ImGuiTreeNodeFlags_NavLeftJumpsToParent; // Left arrow support + tree_flags |= ImGuiTreeNodeFlags_SpanFullWidth; // Span full width for easier mouse reach + tree_flags |= ImGuiTreeNodeFlags_DrawLinesToNodes; // Always draw hierarchy outlines if (node == VisibleNode) tree_flags |= ImGuiTreeNodeFlags_Selected; if (node->Childs.Size == 0) @@ -10844,7 +10994,7 @@ struct ExampleAssetsBrowser Selection.Clear(); } - // Logic would be written in the main code BeginChild() and outputing to local variables. + // Logic would be written in the main code BeginChild() and outputting to local variables. // We extracted it into a function so we can call it easily from multiple places. void UpdateLayoutSizes(float avail_width) { @@ -11154,9 +11304,8 @@ void ImGui::ShowAboutWindow(bool*) {} void ImGui::ShowDemoWindow(bool*) {} void ImGui::ShowUserGuide() {} void ImGui::ShowStyleEditor(ImGuiStyle*) {} -bool ImGui::ShowStyleSelector(const char* label) { return false; } -void ImGui::ShowFontSelector(const char* label) {} +bool ImGui::ShowStyleSelector(const char*) { return false; } -#endif +#endif // #ifndef IMGUI_DISABLE_DEMO_WINDOWS #endif // #ifndef IMGUI_DISABLE diff --git a/lib/third_party/imgui/imgui/source/imgui_draw.cpp b/lib/third_party/imgui/imgui/source/imgui_draw.cpp index 64ae7555e..89fd5e964 100644 --- a/lib/third_party/imgui/imgui/source/imgui_draw.cpp +++ b/lib/third_party/imgui/imgui/source/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91.9b +// dear imgui, v1.92.1 // (drawing and font code) /* @@ -15,7 +15,8 @@ Index of this file: // [SECTION] Helpers ShadeVertsXXX functions // [SECTION] ImFontAtlasShadowTexConfig // [SECTION] ImFontConfig -// [SECTION] ImFontAtlas +// [SECTION] ImFontAtlas, ImFontAtlasBuilder +// [SECTION] ImFontAtlas: backend for stb_truetype // [SECTION] ImFontAtlas: glyph ranges helpers // [SECTION] ImFontGlyphRangesBuilder // [SECTION] ImFont @@ -41,6 +42,7 @@ Index of this file: #endif #include // vsnprintf, sscanf, printf +#include // intptr_t // Visual Studio warnings #ifdef _MSC_VER @@ -219,6 +221,7 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.20f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_InputTextCursor] = colors[ImGuiCol_Text]; colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f); colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); @@ -239,6 +242,7 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.06f); colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive]; colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); + colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border]; colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); colors[ImGuiCol_NavCursor] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); @@ -285,6 +289,7 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst) colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.10f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.78f, 0.82f, 1.00f, 0.60f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.78f, 0.82f, 1.00f, 0.90f); + colors[ImGuiCol_InputTextCursor] = colors[ImGuiCol_Text]; colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f); colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); @@ -305,6 +310,7 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst) colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f); colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive]; colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); + colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border]; colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); colors[ImGuiCol_NavCursor] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); @@ -352,6 +358,7 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_ResizeGrip] = ImVec4(0.35f, 0.35f, 0.35f, 0.17f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_InputTextCursor] = colors[ImGuiCol_Text]; colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.90f); colors[ImGuiCol_TabSelected] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); @@ -372,6 +379,7 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_TableRowBgAlt] = ImVec4(0.30f, 0.30f, 0.30f, 0.09f); colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive]; colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); + colors[ImGuiCol_TreeLines] = colors[ImGuiCol_Border]; colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); colors[ImGuiCol_NavCursor] = colors[ImGuiCol_HeaderHovered]; colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f); @@ -420,6 +428,11 @@ ImDrawListSharedData::ImDrawListSharedData() ArcFastRadiusCutoff = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(IM_DRAWLIST_ARCFAST_SAMPLE_MAX, CircleSegmentMaxError); } +ImDrawListSharedData::~ImDrawListSharedData() +{ + IM_ASSERT(DrawLists.Size == 0); +} + void ImDrawListSharedData::SetCircleTessellationMaxError(float max_error) { if (CircleSegmentMaxError == max_error) @@ -438,22 +451,32 @@ void ImDrawListSharedData::SetCircleTessellationMaxError(float max_error) ImDrawList::ImDrawList(ImDrawListSharedData* shared_data) { memset(this, 0, sizeof(*this)); - _Data = shared_data; + _SetDrawListSharedData(shared_data); } ImDrawList::~ImDrawList() { _ClearFreeMemory(); + _SetDrawListSharedData(NULL); +} + +void ImDrawList::_SetDrawListSharedData(ImDrawListSharedData* data) +{ + if (_Data != NULL) + _Data->DrawLists.find_erase_unsorted(this); + _Data = data; + if (_Data != NULL) + _Data->DrawLists.push_back(this); } // Initialize before use in a new frame. We always have a command ready in the buffer. -// In the majority of cases, you would want to call PushClipRect() and PushTextureID() after this. +// In the majority of cases, you would want to call PushClipRect() and PushTexture() after this. void ImDrawList::_ResetForNewFrame() { // Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory. IM_STATIC_ASSERT(offsetof(ImDrawCmd, ClipRect) == 0); - IM_STATIC_ASSERT(offsetof(ImDrawCmd, TextureId) == sizeof(ImVec4)); - IM_STATIC_ASSERT(offsetof(ImDrawCmd, VtxOffset) == sizeof(ImVec4) + sizeof(ImTextureID)); + IM_STATIC_ASSERT(offsetof(ImDrawCmd, TexRef) == sizeof(ImVec4)); + IM_STATIC_ASSERT(offsetof(ImDrawCmd, VtxOffset) == sizeof(ImVec4) + sizeof(ImTextureRef)); if (_Splitter._Count > 1) _Splitter.Merge(this); @@ -466,7 +489,7 @@ void ImDrawList::_ResetForNewFrame() _VtxWritePtr = NULL; _IdxWritePtr = NULL; _ClipRectStack.resize(0); - _TextureIdStack.resize(0); + _TextureStack.resize(0); _CallbacksDataBuf.resize(0); _Path.resize(0); _Splitter.Clear(); @@ -484,7 +507,7 @@ void ImDrawList::_ClearFreeMemory() _VtxWritePtr = NULL; _IdxWritePtr = NULL; _ClipRectStack.clear(); - _TextureIdStack.clear(); + _TextureStack.clear(); _CallbacksDataBuf.clear(); _Path.clear(); _Splitter.ClearFreeMemory(); @@ -504,7 +527,7 @@ void ImDrawList::AddDrawCmd() { ImDrawCmd draw_cmd; draw_cmd.ClipRect = _CmdHeader.ClipRect; // Same as calling ImDrawCmd_HeaderCopy() - draw_cmd.TextureId = _CmdHeader.TextureId; + draw_cmd.TexRef = _CmdHeader.TexRef; draw_cmd.VtxOffset = _CmdHeader.VtxOffset; draw_cmd.IdxOffset = IdxBuffer.Size; @@ -559,10 +582,10 @@ void ImDrawList::AddCallback(ImDrawCallback callback, void* userdata, size_t use AddDrawCmd(); // Force a new command after us (see comment below) } -// Compare ClipRect, TextureId and VtxOffset with a single memcmp() +// Compare ClipRect, TexRef and VtxOffset with a single memcmp() #define ImDrawCmd_HeaderSize (offsetof(ImDrawCmd, VtxOffset) + sizeof(unsigned int)) -#define ImDrawCmd_HeaderCompare(CMD_LHS, CMD_RHS) (memcmp(CMD_LHS, CMD_RHS, ImDrawCmd_HeaderSize)) // Compare ClipRect, TextureId, VtxOffset -#define ImDrawCmd_HeaderCopy(CMD_DST, CMD_SRC) (memcpy(CMD_DST, CMD_SRC, ImDrawCmd_HeaderSize)) // Copy ClipRect, TextureId, VtxOffset +#define ImDrawCmd_HeaderCompare(CMD_LHS, CMD_RHS) (memcmp(CMD_LHS, CMD_RHS, ImDrawCmd_HeaderSize)) // Compare ClipRect, TexRef, VtxOffset +#define ImDrawCmd_HeaderCopy(CMD_DST, CMD_SRC) (memcpy(CMD_DST, CMD_SRC, ImDrawCmd_HeaderSize)) // Copy ClipRect, TexRef, VtxOffset #define ImDrawCmd_AreSequentialIdxOffset(CMD_0, CMD_1) (CMD_0->IdxOffset + CMD_0->ElemCount == CMD_1->IdxOffset) // Try to merge two last draw commands @@ -602,17 +625,20 @@ void ImDrawList::_OnChangedClipRect() curr_cmd->ClipRect = _CmdHeader.ClipRect; } -void ImDrawList::_OnChangedTextureID() +void ImDrawList::_OnChangedTexture() { // If current command is used with different settings we need to add a new command IM_ASSERT_PARANOID(CmdBuffer.Size > 0); ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; - if (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != _CmdHeader.TextureId) + if (curr_cmd->ElemCount != 0 && curr_cmd->TexRef != _CmdHeader.TexRef) { AddDrawCmd(); return; } - IM_ASSERT(curr_cmd->UserCallback == NULL); + + // Unlike other _OnChangedXXX functions this may be called by ImFontAtlasUpdateDrawListsTextures() in more locations so we need to handle this case. + if (curr_cmd->UserCallback != NULL) + return; // Try to merge with previous command if it matches, else use current command ImDrawCmd* prev_cmd = curr_cmd - 1; @@ -621,7 +647,7 @@ void ImDrawList::_OnChangedTextureID() CmdBuffer.pop_back(); return; } - curr_cmd->TextureId = _CmdHeader.TextureId; + curr_cmd->TexRef = _CmdHeader.TexRef; } void ImDrawList::_OnChangedVtxOffset() @@ -682,27 +708,30 @@ void ImDrawList::PopClipRect() _OnChangedClipRect(); } -void ImDrawList::PushTextureID(ImTextureID texture_id) +void ImDrawList::PushTexture(ImTextureRef tex_ref) { - _TextureIdStack.push_back(texture_id); - _CmdHeader.TextureId = texture_id; - _OnChangedTextureID(); + _TextureStack.push_back(tex_ref); + _CmdHeader.TexRef = tex_ref; + if (tex_ref._TexData != NULL) + IM_ASSERT(tex_ref._TexData->WantDestroyNextFrame == false); + _OnChangedTexture(); } -void ImDrawList::PopTextureID() +void ImDrawList::PopTexture() { - _TextureIdStack.pop_back(); - _CmdHeader.TextureId = (_TextureIdStack.Size == 0) ? (ImTextureID)NULL : _TextureIdStack.Data[_TextureIdStack.Size - 1]; - _OnChangedTextureID(); + _TextureStack.pop_back(); + _CmdHeader.TexRef = (_TextureStack.Size == 0) ? ImTextureRef() : _TextureStack.Data[_TextureStack.Size - 1]; + _OnChangedTexture(); } -// This is used by ImGui::PushFont()/PopFont(). It works because we never use _TextureIdStack[] elsewhere than in PushTextureID()/PopTextureID(). -void ImDrawList::_SetTextureID(ImTextureID texture_id) +// This is used by ImGui::PushFont()/PopFont(). It works because we never use _TextureIdStack[] elsewhere than in PushTexture()/PopTexture(). +void ImDrawList::_SetTexture(ImTextureRef tex_ref) { - if (_CmdHeader.TextureId == texture_id) + if (_CmdHeader.TexRef == tex_ref) return; - _CmdHeader.TextureId = texture_id; - _OnChangedTextureID(); + _CmdHeader.TexRef = tex_ref; + _TextureStack.back() = tex_ref; + _OnChangedTexture(); } // Reserve space for a number of vertices and indices. @@ -888,7 +917,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 dm_x *= half_draw_size; // dm_x, dm_y are offset to the outer edge of the AA area dm_y *= half_draw_size; - // Add temporary vertexes for the outer edges + // Add temporary vertices for the outer edges ImVec2* out_vtx = &temp_points[i2 * 2]; out_vtx[0].x = points[i2].x + dm_x; out_vtx[0].y = points[i2].y + dm_y; @@ -915,7 +944,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 idx1 = idx2; } - // Add vertexes for each point on the line + // Add vertices for each point on the line if (use_texture) { // If we're using textures we only need to emit the left/right edge vertices @@ -1715,8 +1744,6 @@ void ImDrawList::AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 if (font_size == 0.0f) font_size = _Data->FontSize; - IM_ASSERT(font->ContainerAtlas->TexID == _CmdHeader.TextureId); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. - ImVec4 clip_rect = _CmdHeader.ClipRect; if (cpu_fine_clip_rect) { @@ -1729,9 +1756,9 @@ void ImDrawList::AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 // IMHEX PATCH BEGIN int flags; bool is_subpixel = false; - if (font != nullptr && font->ContainerAtlas != nullptr) { - flags = font->ContainerAtlas->FontBuilderFlags; - is_subpixel = (flags & ImGuiFreeTypeBuilderFlags_SubPixel) != 0; + if (font != nullptr && !font->Sources.empty()) { + flags = font->Sources[0]->FontLoaderFlags; + is_subpixel = (flags & ImGuiFreeTypeLoaderFlags_SubPixel) != 0; } void ImGui_ImplOpenGL3_TurnFontShadersOn(const ImDrawList *parent_list, const ImDrawCmd *cmd); @@ -1756,39 +1783,39 @@ void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, c AddText(_Data->Font, _Data->FontSize, pos, col, text_begin, text_end); } -void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col) +void ImDrawList::AddImage(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col) { if ((col & IM_COL32_A_MASK) == 0) return; - const bool push_texture_id = user_texture_id != _CmdHeader.TextureId; + const bool push_texture_id = tex_ref != _CmdHeader.TexRef; if (push_texture_id) - PushTextureID(user_texture_id); + PushTexture(tex_ref); PrimReserve(6, 4); PrimRectUV(p_min, p_max, uv_min, uv_max, col); if (push_texture_id) - PopTextureID(); + PopTexture(); } -void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1, const ImVec2& uv2, const ImVec2& uv3, const ImVec2& uv4, ImU32 col) +void ImDrawList::AddImageQuad(ImTextureRef tex_ref, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1, const ImVec2& uv2, const ImVec2& uv3, const ImVec2& uv4, ImU32 col) { if ((col & IM_COL32_A_MASK) == 0) return; - const bool push_texture_id = user_texture_id != _CmdHeader.TextureId; + const bool push_texture_id = tex_ref != _CmdHeader.TexRef; if (push_texture_id) - PushTextureID(user_texture_id); + PushTexture(tex_ref); PrimReserve(6, 4); PrimQuadUV(p1, p2, p3, p4, uv1, uv2, uv3, uv4, col); if (push_texture_id) - PopTextureID(); + PopTexture(); } -void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags) +void ImDrawList::AddImageRounded(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) return; @@ -1796,13 +1823,13 @@ void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_mi flags = FixRectCornerFlags(flags); if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { - AddImage(user_texture_id, p_min, p_max, uv_min, uv_max, col); + AddImage(tex_ref, p_min, p_max, uv_min, uv_max, col); return; } - const bool push_texture_id = user_texture_id != _CmdHeader.TextureId; + const bool push_texture_id = tex_ref != _CmdHeader.TexRef; if (push_texture_id) - PushTextureID(user_texture_id); + PushTexture(tex_ref); int vert_start_idx = VtxBuffer.Size; PathRect(p_min, p_max, rounding, flags); @@ -1811,7 +1838,7 @@ void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_mi ImGui::ShadeVertsLinearUV(this, vert_start_idx, vert_end_idx, p_min, p_max, uv_min, uv_max, true); if (push_texture_id) - PopTextureID(); + PopTexture(); } //----------------------------------------------------------------------------- @@ -2596,8 +2623,8 @@ void ImDrawList::AddShadowConvexPoly(const ImVec2* points, int points_count, ImU const ImVec4 uvs = _Data->ShadowRectUvs[9]; - int tex_width = _Data->Font->ContainerAtlas->TexWidth; - int tex_height = _Data->Font->ContainerAtlas->TexHeight; + int tex_width = _Data->Font->ContainerAtlas->TexData->Width; + int tex_height = _Data->Font->ContainerAtlas->TexData->Height; float inv_tex_width = 1.0f / (float)tex_width; float inv_tex_height = 1.0f / (float)tex_height; @@ -2957,7 +2984,7 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) // If current command is used with different settings we need to add a new command ImDrawCmd* curr_cmd = &draw_list->CmdBuffer.Data[draw_list->CmdBuffer.Size - 1]; if (curr_cmd->ElemCount == 0) - ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset + ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TexRef, VtxOffset else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0) draw_list->AddDrawCmd(); @@ -2983,7 +3010,7 @@ void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx) if (curr_cmd == NULL) draw_list->AddDrawCmd(); else if (curr_cmd->ElemCount == 0) - ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset + ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TexRef, VtxOffset else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0) draw_list->AddDrawCmd(); } @@ -2999,6 +3026,7 @@ void ImDrawData::Clear() CmdLists.resize(0); // The ImDrawList are NOT owned by ImDrawData but e.g. by ImGuiContext, so we don't clear them. DisplayPos = DisplaySize = FramebufferScale = ImVec2(0.0f, 0.0f); OwnerViewport = NULL; + Textures = NULL; } // Important: 'out_list' is generally going to be draw_data->CmdLists, but may be another temporary list @@ -3149,6 +3177,7 @@ void ImGui::ShadeVertsTransformPos(ImDrawList* draw_list, int vert_start_idx, in // [SECTION] ImFontConfig //----------------------------------------------------------------------------- +// FIXME-NEWATLAS: Oversample specification could be more dynamic. For now, favoring automatic selection. ImFontConfig::ImFontConfig() { memset(this, 0, sizeof(*this)); @@ -3162,39 +3191,155 @@ ImFontConfig::ImFontConfig() } //----------------------------------------------------------------------------- -// [SECTION] ImFontAtlas +// [SECTION] ImTextureData +//----------------------------------------------------------------------------- +// - ImTextureData::Create() +// - ImTextureData::DestroyPixels() +//----------------------------------------------------------------------------- + +int ImTextureDataGetFormatBytesPerPixel(ImTextureFormat format) +{ + switch (format) + { + case ImTextureFormat_Alpha8: return 1; + case ImTextureFormat_RGBA32: return 4; + } + IM_ASSERT(0); + return 0; +} + +const char* ImTextureDataGetStatusName(ImTextureStatus status) +{ + switch (status) + { + case ImTextureStatus_OK: return "OK"; + case ImTextureStatus_Destroyed: return "Destroyed"; + case ImTextureStatus_WantCreate: return "WantCreate"; + case ImTextureStatus_WantUpdates: return "WantUpdates"; + case ImTextureStatus_WantDestroy: return "WantDestroy"; + } + return "N/A"; +} + +const char* ImTextureDataGetFormatName(ImTextureFormat format) +{ + switch (format) + { + case ImTextureFormat_Alpha8: return "Alpha8"; + case ImTextureFormat_RGBA32: return "RGBA32"; + } + return "N/A"; +} + +void ImTextureData::Create(ImTextureFormat format, int w, int h) +{ + DestroyPixels(); + Format = format; + Width = w; + Height = h; + BytesPerPixel = ImTextureDataGetFormatBytesPerPixel(format); + UseColors = false; + Pixels = (unsigned char*)IM_ALLOC(Width * Height * BytesPerPixel); + IM_ASSERT(Pixels != NULL); + memset(Pixels, 0, Width * Height * BytesPerPixel); + UsedRect.x = UsedRect.y = UsedRect.w = UsedRect.h = 0; + UpdateRect.x = UpdateRect.y = (unsigned short)~0; + UpdateRect.w = UpdateRect.h = 0; +} + +void ImTextureData::DestroyPixels() +{ + if (Pixels) + IM_FREE(Pixels); + Pixels = NULL; + UseColors = false; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImFontAtlas, ImFontAtlasBuilder //----------------------------------------------------------------------------- // - Default texture data encoded in ASCII +// - ImFontAtlas() +// - ImFontAtlas::Clear() +// - ImFontAtlas::CompactCache() // - ImFontAtlas::ClearInputData() // - ImFontAtlas::ClearTexData() // - ImFontAtlas::ClearFonts() -// - ImFontAtlas::Clear() -// - ImFontAtlas::GetTexDataAsAlpha8() -// - ImFontAtlas::GetTexDataAsRGBA32() +//----------------------------------------------------------------------------- +// - ImFontAtlasUpdateNewFrame() +// - ImFontAtlasTextureBlockConvert() +// - ImFontAtlasTextureBlockPostProcess() +// - ImFontAtlasTextureBlockPostProcessMultiply() +// - ImFontAtlasTextureBlockFill() +// - ImFontAtlasTextureBlockCopy() +// - ImFontAtlasTextureBlockQueueUpload() +//----------------------------------------------------------------------------- +// - ImFontAtlas::GetTexDataAsAlpha8() [legacy] +// - ImFontAtlas::GetTexDataAsRGBA32() [legacy] +// - ImFontAtlas::Build() [legacy] +//----------------------------------------------------------------------------- // - ImFontAtlas::AddFont() // - ImFontAtlas::AddFontDefault() // - ImFontAtlas::AddFontFromFileTTF() // - ImFontAtlas::AddFontFromMemoryTTF() // - ImFontAtlas::AddFontFromMemoryCompressedTTF() // - ImFontAtlas::AddFontFromMemoryCompressedBase85TTF() -// - ImFontAtlas::AddCustomRectRegular() -// - ImFontAtlas::AddCustomRectFontGlyph() -// - ImFontAtlas::CalcCustomRectUV() +// - ImFontAtlas::RemoveFont() +// - ImFontAtlasBuildNotifySetFont() +//----------------------------------------------------------------------------- +// - ImFontAtlas::AddCustomRect() +// - ImFontAtlas::RemoveCustomRect() +// - ImFontAtlas::GetCustomRect() +// - ImFontAtlas::AddCustomRectFontGlyph() [legacy] +// - ImFontAtlas::AddCustomRectFontGlyphForSize() [legacy] // - ImFontAtlasGetMouseCursorTexData() -// - ImFontAtlas::Build() -// - ImFontAtlasBuildMultiplyCalcLookupTable() -// - ImFontAtlasBuildMultiplyRectAlpha8() -// - ImFontAtlasBuildWithStbTruetype() -// - ImFontAtlasGetBuilderForStbTruetype() -// - ImFontAtlasUpdateSourcesPointers() -// - ImFontAtlasBuildSetupFont() -// - ImFontAtlasBuildPackCustomRects() -// - ImFontAtlasBuildRender8bppRectFromString() -// - ImFontAtlasBuildRender32bppRectFromString() -// - ImFontAtlasBuildRenderDefaultTexData() -// - ImFontAtlasBuildRenderLinesTexData() +//----------------------------------------------------------------------------- +// - ImFontAtlasBuildMain() +// - ImFontAtlasBuildSetupFontLoader() +// - ImFontAtlasBuildPreloadAllGlyphRanges() +// - ImFontAtlasBuildUpdatePointers() +// - ImFontAtlasBuildRenderBitmapFromString() +// - ImFontAtlasBuildUpdateBasicTexData() +// - ImFontAtlasBuildUpdateLinesTexData() +// - ImFontAtlasBuildAddFont() +// - ImFontAtlasBuildSetupFontBakedEllipsis() +// - ImFontAtlasBuildSetupFontBakedBlanks() +// - ImFontAtlasBuildSetupFontBakedFallback() +// - ImFontAtlasBuildSetupFontSpecialGlyphs() +// - ImFontAtlasBuildDiscardBakes() +// - ImFontAtlasBuildDiscardFontBakedGlyph() +// - ImFontAtlasBuildDiscardFontBaked() +// - ImFontAtlasBuildDiscardFontBakes() +//----------------------------------------------------------------------------- +// - ImFontAtlasAddDrawListSharedData() +// - ImFontAtlasRemoveDrawListSharedData() +// - ImFontAtlasUpdateDrawListsTextures() +// - ImFontAtlasUpdateDrawListsSharedData() +//----------------------------------------------------------------------------- +// - ImFontAtlasBuildSetTexture() +// - ImFontAtlasBuildAddTexture() +// - ImFontAtlasBuildMakeSpace() +// - ImFontAtlasBuildRepackTexture() +// - ImFontAtlasBuildGrowTexture() +// - ImFontAtlasBuildRepackOrGrowTexture() +// - ImFontAtlasBuildGetTextureSizeEstimate() +// - ImFontAtlasBuildCompactTexture() // - ImFontAtlasBuildInit() -// - ImFontAtlasBuildFinish() +// - ImFontAtlasBuildDestroy() +//----------------------------------------------------------------------------- +// - ImFontAtlasPackInit() +// - ImFontAtlasPackAllocRectEntry() +// - ImFontAtlasPackReuseRectEntry() +// - ImFontAtlasPackDiscardRect() +// - ImFontAtlasPackAddRect() +// - ImFontAtlasPackGetRect() +//----------------------------------------------------------------------------- +// - ImFontBaked_BuildGrowIndex() +// - ImFontBaked_BuildLoadGlyph() +// - ImFontBaked_BuildLoadGlyphAdvanceX() +// - ImFontAtlasDebugLogTextureRequests() +//----------------------------------------------------------------------------- +// - ImFontAtlasGetFontLoaderForStbTruetype() //----------------------------------------------------------------------------- // A work of art lies ahead! (. = white layer, X = black layer, others are blank) @@ -3249,146 +3394,468 @@ static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3 { ImVec2(109,0),ImVec2(13,15), ImVec2( 6, 7) }, // ImGuiMouseCursor_NotAllowed }; +#define IM_FONTGLYPH_INDEX_UNUSED ((ImU16)-1) // 0xFFFF +#define IM_FONTGLYPH_INDEX_NOT_FOUND ((ImU16)-2) // 0xFFFE + ImFontAtlas::ImFontAtlas() { memset(this, 0, sizeof(*this)); + TexDesiredFormat = ImTextureFormat_RGBA32; TexGlyphPadding = 1; - PackIdMouseCursors = PackIdLines = -1; + TexMinWidth = 512; + TexMinHeight = 128; + TexMaxWidth = 8192; + TexMaxHeight = 8192; + RendererHasTextures = false; // Assumed false by default, as apps can call e.g Atlas::Build() after backend init and before ImGui can update. + TexNextUniqueID = 1; + FontNextUniqueID = 1; + Builder = NULL; + + // FIXME-SHADOWS: move elsewhere? ShadowRectIds[0] = ShadowRectIds[1] = -1; ShadowTexConfig.SetupDefaults(); } ImFontAtlas::~ImFontAtlas() { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); - Clear(); + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + RendererHasTextures = false; // Full Clear() is supported, but ClearTexData() only isn't. + ClearFonts(); + ClearTexData(); + TexList.clear_delete(); + TexData = NULL; } -void ImFontAtlas::ClearInputData() +void ImFontAtlas::Clear() { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); - for (ImFontConfig& font_cfg : Sources) - if (font_cfg.FontData && font_cfg.FontDataOwnedByAtlas) - { - IM_FREE(font_cfg.FontData); - font_cfg.FontData = NULL; - } + bool backup_renderer_has_textures = RendererHasTextures; + RendererHasTextures = false; // Full Clear() is supported, but ClearTexData() only isn't. + ClearFonts(); + ClearTexData(); + RendererHasTextures = backup_renderer_has_textures; +} + +void ImFontAtlas::CompactCache() +{ + ImFontAtlasTextureCompact(this); +} + +void ImFontAtlas::SetFontLoader(const ImFontLoader* font_loader) +{ + ImFontAtlasBuildSetupFontLoader(this, font_loader); +} + +void ImFontAtlas::ClearInputData() +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); - // When clearing this we lose access to the font name and other information used to build the font. for (ImFont* font : Fonts) - if (font->Sources >= Sources.Data && font->Sources < Sources.Data + Sources.Size) - { - font->Sources = NULL; - font->SourcesCount = 0; - } + ImFontAtlasFontDestroyOutput(this, font); + for (ImFontConfig& font_cfg : Sources) + ImFontAtlasFontDestroySourceData(this, &font_cfg); + for (ImFont* font : Fonts) + { + // When clearing this we lose access to the font name and other information used to build the font. + font->Sources.clear(); + font->Flags |= ImFontFlags_NoLoadGlyphs; + } Sources.clear(); - CustomRects.clear(); - PackIdMouseCursors = PackIdLines = -1; + + // FIXME-SHADOWS: Move elsewhere? ShadowRectIds[0] = ShadowRectIds[1] = -1; - // Important: we leave TexReady untouched } -void ImFontAtlas::ClearTexData() +// Clear CPU-side copy of the texture data. +void ImFontAtlas::ClearTexData() { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); - if (TexPixelsAlpha8) - IM_FREE(TexPixelsAlpha8); - if (TexPixelsRGBA32) - IM_FREE(TexPixelsRGBA32); - TexPixelsAlpha8 = NULL; - TexPixelsRGBA32 = NULL; - TexPixelsUseColors = false; - // Important: we leave TexReady untouched + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + IM_ASSERT(RendererHasTextures == false && "Not supported for dynamic atlases, but you may call Clear()."); + for (ImTextureData* tex : TexList) + tex->DestroyPixels(); + //Locked = true; // Hoped to be able to lock this down but some reload patterns may not be happy with it. } -void ImFontAtlas::ClearFonts() +void ImFontAtlas::ClearFonts() { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + // FIXME-NEWATLAS: Illegal to remove currently bound font. + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + ImFontAtlasBuildDestroy(this); ClearInputData(); Fonts.clear_delete(); - TexReady = false; -} - -void ImFontAtlas::Clear() -{ - ClearInputData(); - ClearTexData(); - ClearFonts(); -} - -void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) -{ - // Build atlas on demand - if (TexPixelsAlpha8 == NULL) - Build(); - - *out_pixels = TexPixelsAlpha8; - if (out_width) *out_width = TexWidth; - if (out_height) *out_height = TexHeight; - if (out_bytes_per_pixel) *out_bytes_per_pixel = 1; -} - -void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) -{ - // Convert to RGBA32 format on demand - // Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp - if (!TexPixelsRGBA32) - { - unsigned char* pixels = NULL; - GetTexDataAsAlpha8(&pixels, NULL, NULL); - if (pixels) + TexIsBuilt = false; + for (ImDrawListSharedData* shared_data : DrawListSharedDatas) + if (shared_data->FontAtlas == this) { - TexPixelsRGBA32 = (unsigned int*)IM_ALLOC((size_t)TexWidth * (size_t)TexHeight * 4); - const unsigned char* src = pixels; - unsigned int* dst = TexPixelsRGBA32; - for (int n = TexWidth * TexHeight; n > 0; n--) - *dst++ = IM_COL32(255, 255, 255, (unsigned int)(*src++)); + shared_data->Font = NULL; + shared_data->FontScale = shared_data->FontSize = 0.0f; + } +} + +static void ImFontAtlasBuildUpdateRendererHasTexturesFromContext(ImFontAtlas* atlas) +{ + // [LEGACY] Copy back the ImGuiBackendFlags_RendererHasTextures flag from ImGui context. + // - This is the 1% exceptional case where that dependency if useful, to bypass an issue where otherwise at the + // time of an early call to Build(), it would be impossible for us to tell if the backend supports texture update. + // - Without this hack, we would have quite a pitfall as many legacy codebases have an early call to Build(). + // Whereas conversely, the portion of people using ImDrawList without ImGui is expected to be pathologically rare. + for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) + if (ImGuiContext* imgui_ctx = shared_data->Context) + { + atlas->RendererHasTextures = (imgui_ctx->IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) != 0; + break; + } +} + +// Called by NewFrame() for atlases owned by a context. +// If you manually manage font atlases, you'll need to call this yourself. +// - 'frame_count' needs to be provided because we can gc/prioritize baked fonts based on their age. +// - 'frame_count' may not match those of all imgui contexts using this atlas, as contexts may be updated as different frequencies. But generally you can use ImGui::GetFrameCount() on one of your context. +void ImFontAtlasUpdateNewFrame(ImFontAtlas* atlas, int frame_count, bool renderer_has_textures) +{ + IM_ASSERT(atlas->Builder == NULL || atlas->Builder->FrameCount < frame_count); // Protection against being called twice. + atlas->RendererHasTextures = renderer_has_textures; + + // Check that font atlas was built or backend support texture reload in which case we can build now + if (atlas->RendererHasTextures) + { + atlas->TexIsBuilt = true; + if (atlas->Builder == NULL) // This will only happen if fonts were not already loaded. + ImFontAtlasBuildMain(atlas); + } + else // Legacy backend + { + IM_ASSERT_USER_ERROR(atlas->TexIsBuilt, "Backend does not support ImGuiBackendFlags_RendererHasTextures, and font atlas is not built! Update backend OR make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()."); + } + if (atlas->TexIsBuilt && atlas->Builder->PreloadedAllGlyphsRanges) + IM_ASSERT_USER_ERROR(atlas->RendererHasTextures == false, "Called ImFontAtlas::Build() before ImGuiBackendFlags_RendererHasTextures got set! With new backends: you don't need to call Build()."); + + // Clear BakedCurrent cache, this is important because it ensure the uncached path gets taken once. + // We also rely on ImFontBaked* pointers never crossing frames. + ImFontAtlasBuilder* builder = atlas->Builder; + builder->FrameCount = frame_count; + for (ImFont* font : atlas->Fonts) + font->LastBaked = NULL; + + // Garbage collect BakedPool + if (builder->BakedDiscardedCount > 0) + { + int dst_n = 0, src_n = 0; + for (; src_n < builder->BakedPool.Size; src_n++) + { + ImFontBaked* p_src = &builder->BakedPool[src_n]; + if (p_src->WantDestroy) + continue; + ImFontBaked* p_dst = &builder->BakedPool[dst_n++]; + if (p_dst == p_src) + continue; + memcpy(p_dst, p_src, sizeof(ImFontBaked)); + builder->BakedMap.SetVoidPtr(p_dst->BakedId, p_dst); + } + IM_ASSERT(dst_n + builder->BakedDiscardedCount == src_n); + builder->BakedPool.Size -= builder->BakedDiscardedCount; + builder->BakedDiscardedCount = 0; + } + + // Update texture status + for (int tex_n = 0; tex_n < atlas->TexList.Size; tex_n++) + { + ImTextureData* tex = atlas->TexList[tex_n]; + bool remove_from_list = false; + if (tex->Status == ImTextureStatus_OK) + { + tex->Updates.resize(0); + tex->UpdateRect.x = tex->UpdateRect.y = (unsigned short)~0; + tex->UpdateRect.w = tex->UpdateRect.h = 0; + } + if (tex->Status == ImTextureStatus_WantCreate && atlas->RendererHasTextures) + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL && "Backend set texture's TexID/BackendUserData but did not update Status to OK."); + + if (tex->Status == ImTextureStatus_Destroyed) + { + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL && "Backend set texture Status to Destroyed but did not clear TexID/BackendUserData!"); + if (tex->WantDestroyNextFrame) + remove_from_list = true; // Destroy was scheduled by us + else + tex->Status = ImTextureStatus_WantCreate; // Destroy was done was backend (e.g. freed resources mid-run) + } + else if (tex->WantDestroyNextFrame && tex->Status != ImTextureStatus_WantDestroy) + { + // Request destroy. Keep bool as it allows us to keep track of things. + // We don't destroy pixels right away, as backend may have an in-flight copy from RAM. + IM_ASSERT(tex->Status == ImTextureStatus_OK || tex->Status == ImTextureStatus_WantCreate || tex->Status == ImTextureStatus_WantUpdates); + tex->Status = ImTextureStatus_WantDestroy; + } + + // The backend may need defer destroying by a few frames, to handle texture used by previous in-flight rendering. + // We allow the texture staying in _WantDestroy state and increment a counter which the backend can use to take its decision. + if (tex->Status == ImTextureStatus_WantDestroy) + tex->UnusedFrames++; + + // If a texture has never reached the backend, they don't need to know about it. + if (tex->Status == ImTextureStatus_WantDestroy && tex->TexID == ImTextureID_Invalid && tex->BackendUserData == NULL) + remove_from_list = true; + + // Destroy and remove + if (remove_from_list) + { + tex->DestroyPixels(); + IM_DELETE(tex); + atlas->TexList.erase(atlas->TexList.begin() + tex_n); + tex_n--; } } - - *out_pixels = (unsigned char*)TexPixelsRGBA32; - if (out_width) *out_width = TexWidth; - if (out_height) *out_height = TexHeight; - if (out_bytes_per_pixel) *out_bytes_per_pixel = 4; } -ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) +void ImFontAtlasTextureBlockConvert(const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch, unsigned char* dst_pixels, ImTextureFormat dst_fmt, int dst_pitch, int w, int h) { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); - IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0); - IM_ASSERT(font_cfg->SizePixels > 0.0f && "Is ImFontConfig struct correctly initialized?"); - IM_ASSERT(font_cfg->RasterizerDensity > 0.0f && "Is ImFontConfig struct correctly initialized?"); + IM_ASSERT(src_pixels != NULL && dst_pixels != NULL); + if (src_fmt == dst_fmt) + { + int line_sz = w * ImTextureDataGetFormatBytesPerPixel(src_fmt); + for (int ny = h; ny > 0; ny--, src_pixels += src_pitch, dst_pixels += dst_pitch) + memcpy(dst_pixels, src_pixels, line_sz); + } + else if (src_fmt == ImTextureFormat_Alpha8 && dst_fmt == ImTextureFormat_RGBA32) + { + for (int ny = h; ny > 0; ny--, src_pixels += src_pitch, dst_pixels += dst_pitch) + { + const ImU8* src_p = (const ImU8*)src_pixels; + ImU32* dst_p = (ImU32*)(void*)dst_pixels; + for (int nx = w; nx > 0; nx--) + *dst_p++ = IM_COL32(255, 255, 255, (unsigned int)(*src_p++)); + } + } + else if (src_fmt == ImTextureFormat_RGBA32 && dst_fmt == ImTextureFormat_Alpha8) + { + for (int ny = h; ny > 0; ny--, src_pixels += src_pitch, dst_pixels += dst_pitch) + { + const ImU32* src_p = (const ImU32*)(void*)src_pixels; + ImU8* dst_p = (ImU8*)dst_pixels; + for (int nx = w; nx > 0; nx--) + *dst_p++ = ((*src_p++) >> IM_COL32_A_SHIFT) & 0xFF; + } + } + else + { + IM_ASSERT(0); + } +} + +// Source buffer may be written to (used for in-place mods). +// Post-process hooks may eventually be added here. +void ImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data) +{ + // Multiply operator (legacy) + if (data->FontSrc->RasterizerMultiply != 1.0f) + ImFontAtlasTextureBlockPostProcessMultiply(data, data->FontSrc->RasterizerMultiply); +} + +void ImFontAtlasTextureBlockPostProcessMultiply(ImFontAtlasPostProcessData* data, float multiply_factor) +{ + unsigned char* pixels = (unsigned char*)data->Pixels; + int pitch = data->Pitch; + if (data->Format == ImTextureFormat_Alpha8) + { + for (int ny = data->Height; ny > 0; ny--, pixels += pitch) + { + ImU8* p = (ImU8*)pixels; + for (int nx = data->Width; nx > 0; nx--, p++) + { + unsigned int v = ImMin((unsigned int)(*p * multiply_factor), (unsigned int)255); + *p = (unsigned char)v; + } + } + } + else if (data->Format == ImTextureFormat_RGBA32) //-V547 + { + for (int ny = data->Height; ny > 0; ny--, pixels += pitch) + { + ImU32* p = (ImU32*)(void*)pixels; + for (int nx = data->Width; nx > 0; nx--, p++) + { + unsigned int a = ImMin((unsigned int)(((*p >> IM_COL32_A_SHIFT) & 0xFF) * multiply_factor), (unsigned int)255); + *p = IM_COL32((*p >> IM_COL32_R_SHIFT) & 0xFF, (*p >> IM_COL32_G_SHIFT) & 0xFF, (*p >> IM_COL32_B_SHIFT) & 0xFF, a); + } + } + } + else + { + IM_ASSERT(0); + } +} + +// Fill with single color. We don't use this directly but it is convenient for anyone working on uploading custom rects. +void ImFontAtlasTextureBlockFill(ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h, ImU32 col) +{ + if (dst_tex->Format == ImTextureFormat_Alpha8) + { + ImU8 col_a = (col >> IM_COL32_A_SHIFT) & 0xFF; + for (int y = 0; y < h; y++) + memset((ImU8*)dst_tex->GetPixelsAt(dst_x, dst_y + y), col_a, w); + } + else + { + for (int y = 0; y < h; y++) + { + ImU32* p = (ImU32*)(void*)dst_tex->GetPixelsAt(dst_x, dst_y + y); + for (int x = w; x > 0; x--, p++) + *p = col; + } + } +} + +// Copy block from one texture to another +void ImFontAtlasTextureBlockCopy(ImTextureData* src_tex, int src_x, int src_y, ImTextureData* dst_tex, int dst_x, int dst_y, int w, int h) +{ + IM_ASSERT(src_tex->Pixels != NULL && dst_tex->Pixels != NULL); + IM_ASSERT(src_tex->Format == dst_tex->Format); + IM_ASSERT(src_x >= 0 && src_x + w <= src_tex->Width); + IM_ASSERT(src_y >= 0 && src_y + h <= src_tex->Height); + IM_ASSERT(dst_x >= 0 && dst_x + w <= dst_tex->Width); + IM_ASSERT(dst_y >= 0 && dst_y + h <= dst_tex->Height); + for (int y = 0; y < h; y++) + memcpy(dst_tex->GetPixelsAt(dst_x, dst_y + y), src_tex->GetPixelsAt(src_x, src_y + y), w * dst_tex->BytesPerPixel); +} + +// Queue texture block update for renderer backend +void ImFontAtlasTextureBlockQueueUpload(ImFontAtlas* atlas, ImTextureData* tex, int x, int y, int w, int h) +{ + IM_ASSERT(tex->Status != ImTextureStatus_WantDestroy && tex->Status != ImTextureStatus_Destroyed); + IM_ASSERT(x >= 0 && x <= 0xFFFF && y >= 0 && y <= 0xFFFF && w >= 0 && x + w <= 0x10000 && h >= 0 && y + h <= 0x10000); + IM_UNUSED(atlas); + + ImTextureRect req = { (unsigned short)x, (unsigned short)y, (unsigned short)w, (unsigned short)h }; + int new_x1 = ImMax(tex->UpdateRect.w == 0 ? 0 : tex->UpdateRect.x + tex->UpdateRect.w, req.x + req.w); + int new_y1 = ImMax(tex->UpdateRect.h == 0 ? 0 : tex->UpdateRect.y + tex->UpdateRect.h, req.y + req.h); + tex->UpdateRect.x = ImMin(tex->UpdateRect.x, req.x); + tex->UpdateRect.y = ImMin(tex->UpdateRect.y, req.y); + tex->UpdateRect.w = (unsigned short)(new_x1 - tex->UpdateRect.x); + tex->UpdateRect.h = (unsigned short)(new_y1 - tex->UpdateRect.y); + tex->UsedRect.x = ImMin(tex->UsedRect.x, req.x); + tex->UsedRect.y = ImMin(tex->UsedRect.y, req.y); + tex->UsedRect.w = (unsigned short)(ImMax(tex->UsedRect.x + tex->UsedRect.w, req.x + req.w) - tex->UsedRect.x); + tex->UsedRect.h = (unsigned short)(ImMax(tex->UsedRect.y + tex->UsedRect.h, req.y + req.h) - tex->UsedRect.y); + atlas->TexIsBuilt = false; + + // No need to queue if status is _WantCreate + if (tex->Status == ImTextureStatus_OK || tex->Status == ImTextureStatus_WantUpdates) + { + tex->Status = ImTextureStatus_WantUpdates; + tex->Updates.push_back(req); + } +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +static void GetTexDataAsFormat(ImFontAtlas* atlas, ImTextureFormat format, unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + ImTextureData* tex = atlas->TexData; + if (!atlas->TexIsBuilt || tex == NULL || tex->Pixels == NULL || atlas->TexDesiredFormat != format) + { + atlas->TexDesiredFormat = format; + atlas->Build(); + tex = atlas->TexData; + } + if (out_pixels) { *out_pixels = (unsigned char*)tex->Pixels; }; + if (out_width) { *out_width = tex->Width; }; + if (out_height) { *out_height = tex->Height; }; + if (out_bytes_per_pixel) { *out_bytes_per_pixel = tex->BytesPerPixel; } +} + +void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + GetTexDataAsFormat(this, ImTextureFormat_Alpha8, out_pixels, out_width, out_height, out_bytes_per_pixel); +} + +void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + GetTexDataAsFormat(this, ImTextureFormat_RGBA32, out_pixels, out_width, out_height, out_bytes_per_pixel); +} + +bool ImFontAtlas::Build() +{ + ImFontAtlasBuildMain(this); + return true; +} +#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) +{ + // Sanity Checks + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + IM_ASSERT((font_cfg_in->FontData != NULL && font_cfg_in->FontDataSize > 0) || (font_cfg_in->FontLoader != NULL)); + //IM_ASSERT(font_cfg_in->SizePixels > 0.0f && "Is ImFontConfig struct correctly initialized?"); + IM_ASSERT(font_cfg_in->RasterizerDensity > 0.0f && "Is ImFontConfig struct correctly initialized?"); + if (font_cfg_in->GlyphOffset.x != 0.0f || font_cfg_in->GlyphOffset.y != 0.0f || font_cfg_in->GlyphMinAdvanceX != 0.0f || font_cfg_in->GlyphMaxAdvanceX != FLT_MAX) + IM_ASSERT(font_cfg_in->SizePixels != 0.0f && "Specifying glyph offset/advances requires a reference size to base it on."); + + // Lazily create builder on the first call to AddFont + if (Builder == NULL) + ImFontAtlasBuildInit(this); // Create new font - if (!font_cfg->MergeMode) - Fonts.push_back(IM_NEW(ImFont)); - else - IM_ASSERT(Fonts.Size > 0 && "Cannot use MergeMode for the first font"); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font. - - Sources.push_back(*font_cfg); - ImFontConfig& new_font_cfg = Sources.back(); - if (new_font_cfg.DstFont == NULL) - new_font_cfg.DstFont = Fonts.back(); - if (!new_font_cfg.FontDataOwnedByAtlas) + ImFont* font; + if (!font_cfg_in->MergeMode) { - new_font_cfg.FontData = IM_ALLOC(new_font_cfg.FontDataSize); - new_font_cfg.FontDataOwnedByAtlas = true; - memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize); + font = IM_NEW(ImFont)(); + font->FontId = FontNextUniqueID++; + font->Flags = font_cfg_in->Flags; + font->LegacySize = font_cfg_in->SizePixels; + font->CurrentRasterizerDensity = font_cfg_in->RasterizerDensity; + Fonts.push_back(font); + } + else + { + IM_ASSERT(Fonts.Size > 0 && "Cannot use MergeMode for the first font"); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font. + font = Fonts.back(); } - // Round font size - // - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet. - // - Note that using io.FontGlobalScale or SetWindowFontScale(), with are legacy-ish, partially supported features, can still lead to unrounded sizes. - // - We may support it better later and remove this rounding. - new_font_cfg.SizePixels = ImTrunc(new_font_cfg.SizePixels); + // Add to list + Sources.push_back(*font_cfg_in); + ImFontConfig* font_cfg = &Sources.back(); + if (font_cfg->DstFont == NULL) + font_cfg->DstFont = font; + font->Sources.push_back(font_cfg); + ImFontAtlasBuildUpdatePointers(this); // Pointers to Sources are otherwise dangling after we called Sources.push_back(). - // Pointers to Sources data are otherwise dangling - ImFontAtlasUpdateSourcesPointers(this); + if (font_cfg->FontDataOwnedByAtlas == false) + { + font_cfg->FontDataOwnedByAtlas = true; + font_cfg->FontData = ImMemdup(font_cfg->FontData, (size_t)font_cfg->FontDataSize); + } - // Invalidate texture - TexReady = false; - ClearTexData(); - return new_font_cfg.DstFont; + // Sanity check + // We don't round cfg.SizePixels yet as relative size of merged fonts are used afterwards. + if (font_cfg->GlyphExcludeRanges != NULL) + { + int size = 0; + for (const ImWchar* p = font_cfg->GlyphExcludeRanges; p[0] != 0; p++, size++) {} + IM_ASSERT((size & 1) == 0 && "GlyphExcludeRanges[] size must be multiple of two!"); + IM_ASSERT((size <= 64) && "GlyphExcludeRanges[] size must be small!"); + font_cfg->GlyphExcludeRanges = (ImWchar*)ImMemdup(font_cfg->GlyphExcludeRanges, sizeof(font_cfg->GlyphExcludeRanges[0]) * (size + 1)); + } + if (font_cfg->FontLoader != NULL) + { + IM_ASSERT(font_cfg->FontLoader->FontBakedLoadGlyph != NULL); + IM_ASSERT(font_cfg->FontLoader->LoaderInit == NULL && font_cfg->FontLoader->LoaderShutdown == NULL); // FIXME-NEWATLAS: Unsupported yet. + } + IM_ASSERT(font_cfg->FontLoaderData == NULL); + + if (!ImFontAtlasFontSourceInit(this, font_cfg)) + { + // Rollback (this is a fragile/rarely exercised code-path. TestSuite's "misc_atlas_add_invalid_font" aim to test this) + ImFontAtlasFontDestroySourceData(this, font_cfg); + Sources.pop_back(); + font->Sources.pop_back(); + if (!font_cfg->MergeMode) + { + IM_DELETE(font); + Fonts.pop_back(); + } + return NULL; + } + ImFontAtlasFontSourceAddToFont(this, font, font_cfg); + + return font; } // Default font TTF is compressed with stb_compress then base85 encoded (see misc/fonts/binary_to_compressed_c.cpp for encoder) @@ -3422,9 +3889,9 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) if (font_cfg.SizePixels <= 0.0f) font_cfg.SizePixels = 13.0f * 1.0f; if (font_cfg.Name[0] == '\0') - ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf, %dpx", (int)font_cfg.SizePixels); + ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf"); font_cfg.EllipsisChar = (ImWchar)0x0085; - font_cfg.GlyphOffset.y = 1.0f * IM_TRUNC(font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units + font_cfg.GlyphOffset.y += 1.0f * IM_TRUNC(font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units int ttf_compressed_size = 0; const char* ttf_compressed = GetDefaultCompressedFontDataTTF(&ttf_compressed_size); @@ -3440,12 +3907,16 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); size_t data_size = 0; void* data = ImFileLoadToMemory(filename, "rb", &data_size, 0); if (!data) { - IM_ASSERT_USER_ERROR(0, "Could not load font file!"); + if (font_cfg_template == NULL || (font_cfg_template->Flags & ImFontFlags_NoLoadError) == 0) + { + IMGUI_DEBUG_LOG("While loading '%s'\n", filename); + IM_ASSERT_USER_ERROR(0, "Could not load font file!"); + } return NULL; } ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); @@ -3454,7 +3925,7 @@ ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, // Store a short copy of filename into into the font name for convenience const char* p; for (p = filename + ImStrlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {} - ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s, %.0fpx", p, size_pixels); + ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s", p); } return AddFontFromMemoryTTF(data, (int)data_size, size_pixels, &font_cfg, glyph_ranges); } @@ -3462,7 +3933,7 @@ ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, // NB: Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build(). ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* font_data, int font_data_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); IM_ASSERT(font_cfg.FontData == NULL); IM_ASSERT(font_data_size > 100 && "Incorrect value for font_data_size!"); // Heuristic to prevent accidentally passing a wrong value to font_data_size. @@ -3496,43 +3967,156 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed return font; } -int ImFontAtlas::AddCustomRectRegular(int width, int height) +// On font removal we need to remove references (otherwise we could queue removal?) +// We allow old_font == new_font which forces updating all values (e.g. sizes) +static void ImFontAtlasBuildNotifySetFont(ImFontAtlas* atlas, ImFont* old_font, ImFont* new_font) +{ + for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) + { + if (shared_data->Font == old_font) + shared_data->Font = new_font; + if (ImGuiContext* ctx = shared_data->Context) + { + if (ctx->IO.FontDefault == old_font) + ctx->IO.FontDefault = new_font; + if (ctx->Font == old_font) + { + ImGuiContext* curr_ctx = ImGui::GetCurrentContext(); + bool need_bind_ctx = ctx != curr_ctx; + if (need_bind_ctx) + ImGui::SetCurrentContext(ctx); + ImGui::SetCurrentFont(new_font, ctx->FontSizeBase, ctx->FontSize); + if (need_bind_ctx) + ImGui::SetCurrentContext(curr_ctx); + } + for (ImFontStackData& font_stack_data : ctx->FontStack) + if (font_stack_data.Font == old_font) + font_stack_data.Font = new_font; + } + } +} + +void ImFontAtlas::RemoveFont(ImFont* font) +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas!"); + font->ClearOutputData(); + + ImFontAtlasFontDestroyOutput(this, font); + for (ImFontConfig* src : font->Sources) + ImFontAtlasFontDestroySourceData(this, src); + for (int src_n = 0; src_n < Sources.Size; src_n++) + if (Sources[src_n].DstFont == font) + Sources.erase(&Sources[src_n--]); + + bool removed = Fonts.find_erase(font); + IM_ASSERT(removed); + IM_UNUSED(removed); + + ImFontAtlasBuildUpdatePointers(this); + + font->ContainerAtlas = NULL; + IM_DELETE(font); + + // Notify external systems + ImFont* new_current_font = Fonts.empty() ? NULL : Fonts[0]; + ImFontAtlasBuildNotifySetFont(this, font, new_current_font); +} + +// At it is common to do an AddCustomRect() followed by a GetCustomRect(), we provide an optional 'ImFontAtlasRect* out_r = NULL' argument to retrieve the info straight away. +ImFontAtlasRectId ImFontAtlas::AddCustomRect(int width, int height, ImFontAtlasRect* out_r) { IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); - ImFontAtlasCustomRect r; - r.Width = (unsigned short)width; - r.Height = (unsigned short)height; - CustomRects.push_back(r); - return CustomRects.Size - 1; // Return index + + if (Builder == NULL) + ImFontAtlasBuildInit(this); + + ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); + if (r_id == ImFontAtlasRectId_Invalid) + return ImFontAtlasRectId_Invalid; + if (out_r != NULL) + GetCustomRect(r_id, out_r); + + if (RendererHasTextures) + { + ImTextureRect* r = ImFontAtlasPackGetRect(this, r_id); + ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h); + } + return r_id; } -int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset) +void ImFontAtlas::RemoveCustomRect(ImFontAtlasRectId id) +{ + if (ImFontAtlasPackGetRectSafe(this, id) == NULL) + return; + ImFontAtlasPackDiscardRect(this, id); +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +// This API does not make sense anymore with scalable fonts. +// - Prefer adding a font source (ImFontConfig) using a custom/procedural loader. +// - You may use ImFontFlags_LockBakedSizes to limit an existing font to known baked sizes: +// ImFont* myfont = io.Fonts->AddFontFromFileTTF(....); +// myfont->GetFontBaked(16.0f); +// myfont->Flags |= ImFontFlags_LockBakedSizes; +ImFontAtlasRectId ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset) +{ + float font_size = font->LegacySize; + return AddCustomRectFontGlyphForSize(font, font_size, codepoint, width, height, advance_x, offset); +} +// FIXME: we automatically set glyph.Colored=true by default. +// If you need to alter this, you can write 'font->Glyphs.back()->Colored' after calling AddCustomRectFontGlyph(). +ImFontAtlasRectId ImFontAtlas::AddCustomRectFontGlyphForSize(ImFont* font, float font_size, ImWchar codepoint, int width, int height, float advance_x, const ImVec2& offset) { #ifdef IMGUI_USE_WCHAR32 - IM_ASSERT(id <= IM_UNICODE_CODEPOINT_MAX); + IM_ASSERT(codepoint <= IM_UNICODE_CODEPOINT_MAX); #endif IM_ASSERT(font != NULL); IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); - ImFontAtlasCustomRect r; - r.Width = (unsigned short)width; - r.Height = (unsigned short)height; - r.GlyphID = id; - r.GlyphColored = 0; // Set to 1 manually to mark glyph as colored // FIXME: No official API for that (#8133) - r.GlyphAdvanceX = advance_x; - r.GlyphOffset = offset; - r.Font = font; - CustomRects.push_back(r); - return CustomRects.Size - 1; // Return index -} -void ImFontAtlas::CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const + ImFontBaked* baked = font->GetFontBaked(font_size); + + ImFontAtlasRectId r_id = ImFontAtlasPackAddRect(this, width, height); + if (r_id == ImFontAtlasRectId_Invalid) + return ImFontAtlasRectId_Invalid; + ImTextureRect* r = ImFontAtlasPackGetRect(this, r_id); + if (RendererHasTextures) + ImFontAtlasTextureBlockQueueUpload(this, TexData, r->x, r->y, r->w, r->h); + + if (baked->IsGlyphLoaded(codepoint)) + ImFontAtlasBakedDiscardFontGlyph(this, font, baked, baked->FindGlyph(codepoint)); + + ImFontGlyph glyph; + glyph.Codepoint = codepoint; + glyph.AdvanceX = advance_x; + glyph.X0 = offset.x; + glyph.Y0 = offset.y; + glyph.X1 = offset.x + r->w; + glyph.Y1 = offset.y + r->h; + glyph.Visible = true; + glyph.Colored = true; // FIXME: Arbitrary + glyph.PackId = r_id; + ImFontAtlasBakedAddFontGlyph(this, baked, font->Sources[0], &glyph); + return r_id; +} +#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +bool ImFontAtlas::GetCustomRect(ImFontAtlasRectId id, ImFontAtlasRect* out_r) const { - IM_ASSERT(TexWidth > 0 && TexHeight > 0); // Font atlas needs to be built before we can calculate UV coordinates - IM_ASSERT(rect->IsPacked()); // Make sure the rectangle has been packed - *out_uv_min = ImVec2((float)rect->X * TexUvScale.x, (float)rect->Y * TexUvScale.y); - *out_uv_max = ImVec2((float)(rect->X + rect->Width) * TexUvScale.x, (float)(rect->Y + rect->Height) * TexUvScale.y); + ImTextureRect* r = ImFontAtlasPackGetRectSafe((ImFontAtlas*)this, id); + if (r == NULL) + return false; + IM_ASSERT(TexData->Width > 0 && TexData->Height > 0); // Font atlas needs to be built before we can calculate UV coordinates + if (out_r == NULL) + return true; + out_r->x = r->x; + out_r->y = r->y; + out_r->w = r->w; + out_r->h = r->h; + out_r->uv0 = ImVec2((float)(r->x), (float)(r->y)) * TexUvScale; + out_r->uv1 = ImVec2((float)(r->x + r->w), (float)(r->y + r->h)) * TexUvScale; + return true; } bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]) @@ -3542,9 +4126,8 @@ bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor curso if (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) return false; - IM_ASSERT(atlas->PackIdMouseCursors != -1); - ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdMouseCursors); - ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r->X, (float)r->Y); + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, atlas->Builder->PackIdMouseCursors); + ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r->x, (float)r->y); ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1]; *out_size = size; *out_offset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][2]; @@ -3556,517 +4139,192 @@ bool ImFontAtlasGetMouseCursorTexData(ImFontAtlas* atlas, ImGuiMouseCursor curso return true; } -bool ImFontAtlas::Build() +// When atlas->RendererHasTextures = true, this is only called if no font were loaded. +void ImFontAtlasBuildMain(ImFontAtlas* atlas) { - IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!"); + if (atlas->TexData && atlas->TexData->Format != atlas->TexDesiredFormat) + { + ImVec2i new_tex_size = ImFontAtlasTextureGetSizeEstimate(atlas); + ImFontAtlasBuildDestroy(atlas); + ImFontAtlasTextureAdd(atlas, new_tex_size.x, new_tex_size.y); + } + + if (atlas->Builder == NULL) + ImFontAtlasBuildInit(atlas); // Default font is none are specified - if (Sources.Size == 0) - AddFontDefault(); + if (atlas->Sources.Size == 0) + atlas->AddFontDefault(); - // Select builder - // - Note that we do not reassign to atlas->FontBuilderIO, since it is likely to point to static data which - // may mess with some hot-reloading schemes. If you need to assign to this (for dynamic selection) AND are - // using a hot-reloading scheme that messes up static data, store your own instance of ImFontBuilderIO somewhere - // and point to it instead of pointing directly to return value of the GetBuilderXXX functions. - const ImFontBuilderIO* builder_io = FontBuilderIO; - if (builder_io == NULL) - { -#ifdef IMGUI_ENABLE_FREETYPE - builder_io = ImGuiFreeType::GetBuilderForFreeType(); -#elif defined(IMGUI_ENABLE_STB_TRUETYPE) - builder_io = ImFontAtlasGetBuilderForStbTruetype(); -#else - IM_ASSERT(0); // Invalid Build function -#endif - } - - // Build - return builder_io->FontBuilder_Build(this); + // [LEGACY] For backends not supporting RendererHasTextures: preload all glyphs + ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); + if (atlas->RendererHasTextures == false) // ~ImGuiBackendFlags_RendererHasTextures + ImFontAtlasBuildLegacyPreloadAllGlyphRanges(atlas); + atlas->TexIsBuilt = true; } -void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_brighten_factor) -{ - for (unsigned int i = 0; i < 256; i++) - { - unsigned int value = (unsigned int)(i * in_brighten_factor); - out_table[i] = value > 255 ? 255 : (value & 0xFF); - } -} - -void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride) -{ - IM_ASSERT_PARANOID(w <= stride); - unsigned char* data = pixels + x + y * stride; - for (int j = h; j > 0; j--, data += stride - w) - for (int i = w; i > 0; i--, data++) - *data = table[*data]; -} - -void ImFontAtlasBuildGetOversampleFactors(const ImFontConfig* src, int* out_oversample_h, int* out_oversample_v) +void ImFontAtlasBuildGetOversampleFactors(ImFontConfig* src, ImFontBaked* baked, int* out_oversample_h, int* out_oversample_v) { // Automatically disable horizontal oversampling over size 36 - *out_oversample_h = (src->OversampleH != 0) ? src->OversampleH : (src->SizePixels * src->RasterizerDensity > 36.0f || src->PixelSnapH) ? 1 : 2; + const float raster_size = baked->Size * baked->RasterizerDensity * src->RasterizerDensity; + *out_oversample_h = (src->OversampleH != 0) ? src->OversampleH : (raster_size > 36.0f || src->PixelSnapH) ? 1 : 2; *out_oversample_v = (src->OversampleV != 0) ? src->OversampleV : 1; } -#ifdef IMGUI_ENABLE_STB_TRUETYPE -// Temporary data for one source font (multiple source fonts can be merged into one destination ImFont) -// (C++03 doesn't allow instancing ImVector<> with function-local types so we declare the type here.) -struct ImFontBuildSrcData +// Setup main font loader for the atlas +// Every font source (ImFontConfig) will use this unless ImFontConfig::FontLoader specify a custom loader. +void ImFontAtlasBuildSetupFontLoader(ImFontAtlas* atlas, const ImFontLoader* font_loader) { - stbtt_fontinfo FontInfo; - stbtt_pack_range PackRange; // Hold the list of codepoints to pack (essentially points to Codepoints.Data) - stbrp_rect* Rects; // Rectangle to pack. We first fill in their size and the packer will give us their position. - stbtt_packedchar* PackedChars; // Output glyphs - const ImWchar* SrcRanges; // Ranges as requested by user (user is allowed to request too much, e.g. 0x0020..0xFFFF) - int DstIndex; // Index into atlas->Fonts[] and dst_tmp_array[] - int GlyphsHighest; // Highest requested codepoint - int GlyphsCount; // Glyph count (excluding missing glyphs and glyphs already set by an earlier source font) - ImBitVector GlyphsSet; // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB) - ImVector GlyphsList; // Glyph codepoints list (flattened version of GlyphsSet) -}; + if (atlas->FontLoader == font_loader) + return; + IM_ASSERT(!atlas->Locked && "Cannot modify a locked ImFontAtlas!"); -// Temporary data for one destination ImFont* (multiple source fonts can be merged into one destination ImFont) -struct ImFontBuildDstData -{ - int SrcCount; // Number of source fonts targeting this destination font. - int GlyphsHighest; - int GlyphsCount; - ImBitVector GlyphsSet; // This is used to resolve collision when multiple sources are merged into a same destination font. -}; + for (ImFont* font : atlas->Fonts) + ImFontAtlasFontDestroyOutput(atlas, font); + if (atlas->Builder && atlas->FontLoader && atlas->FontLoader->LoaderShutdown) + atlas->FontLoader->LoaderShutdown(atlas); -static void UnpackBitVectorToFlatIndexList(const ImBitVector* in, ImVector* out) -{ - IM_ASSERT(sizeof(in->Storage.Data[0]) == sizeof(int)); - const ImU32* it_begin = in->Storage.begin(); - const ImU32* it_end = in->Storage.end(); - for (const ImU32* it = it_begin; it < it_end; it++) - if (ImU32 entries_32 = *it) - for (ImU32 bit_n = 0; bit_n < 32; bit_n++) - if (entries_32 & ((ImU32)1 << bit_n)) - out->push_back((int)(((it - it_begin) << 5) + bit_n)); + atlas->FontLoader = font_loader; + atlas->FontLoaderName = font_loader ? font_loader->Name : "NULL"; + IM_ASSERT(atlas->FontLoaderData == NULL); + + if (atlas->Builder && atlas->FontLoader && atlas->FontLoader->LoaderInit) + atlas->FontLoader->LoaderInit(atlas); + for (ImFont* font : atlas->Fonts) + ImFontAtlasFontInitOutput(atlas, font); + for (ImFont* font : atlas->Fonts) + for (ImFontConfig* src : font->Sources) + ImFontAtlasFontSourceAddToFont(atlas, font, src); } -static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) +// Preload all glyph ranges for legacy backends. +// This may lead to multiple texture creation which might be a little slower than before. +void ImFontAtlasBuildLegacyPreloadAllGlyphRanges(ImFontAtlas* atlas) { - IM_ASSERT(atlas->Sources.Size > 0); - - ImFontAtlasBuildInit(atlas); - - // Clear atlas - atlas->TexID = (ImTextureID)NULL; - atlas->TexWidth = atlas->TexHeight = 0; - atlas->TexUvScale = ImVec2(0.0f, 0.0f); - atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f); - atlas->ClearTexData(); - - // Temporary storage for building - ImVector src_tmp_array; - ImVector dst_tmp_array; - src_tmp_array.resize(atlas->Sources.Size); - dst_tmp_array.resize(atlas->Fonts.Size); - memset(src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes()); - memset(dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes()); - - // 1. Initialize font loading structure, check font data validity - for (int src_i = 0; src_i < atlas->Sources.Size; src_i++) + atlas->Builder->PreloadedAllGlyphsRanges = true; + for (ImFont* font : atlas->Fonts) { - ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; - ImFontConfig& src = atlas->Sources[src_i]; - IM_ASSERT(src.DstFont && (!src.DstFont->IsLoaded() || src.DstFont->ContainerAtlas == atlas)); - - // Find index from src.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices) - src_tmp.DstIndex = -1; - for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++) - if (src.DstFont == atlas->Fonts[output_i]) - src_tmp.DstIndex = output_i; - if (src_tmp.DstIndex == -1) + ImFontBaked* baked = font->GetFontBaked(font->LegacySize); + if (font->FallbackChar != 0) + baked->FindGlyph(font->FallbackChar); + if (font->EllipsisChar != 0) + baked->FindGlyph(font->EllipsisChar); + for (ImFontConfig* src : font->Sources) { - IM_ASSERT(src_tmp.DstIndex != -1); // src.DstFont not pointing within atlas->Fonts[] array? - return false; - } - // Initialize helper structure for font loading and verify that the TTF/OTF data is correct - const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)src.FontData, src.FontNo); - IM_ASSERT(font_offset >= 0 && "FontData is incorrect, or FontNo cannot be found."); - if (!stbtt_InitFont(&src_tmp.FontInfo, (unsigned char*)src.FontData, font_offset)) - { - IM_ASSERT(0 && "stbtt_InitFont(): failed to parse FontData. It is correct and complete? Check FontDataSize."); - return false; - } - - // Measure highest codepoints - ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex]; - src_tmp.SrcRanges = src.GlyphRanges ? src.GlyphRanges : atlas->GetGlyphRangesDefault(); - for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) - { - // Check for valid range. This may also help detect *some* dangling pointers, because a common - // user error is to setup ImFontConfig::GlyphRanges with a pointer to data that isn't persistent, - // or to forget to zero-terminate the glyph range array. - IM_ASSERT(src_range[0] <= src_range[1] && "Invalid range: is your glyph range array persistent? it is zero-terminated?"); - src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]); - } - dst_tmp.SrcCount++; - dst_tmp.GlyphsHighest = ImMax(dst_tmp.GlyphsHighest, src_tmp.GlyphsHighest); - } - - // 2. For every requested codepoint, check for their presence in the font data, and handle redundancy or overlaps between source fonts to avoid unused glyphs. - int total_glyphs_count = 0; - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; - ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex]; - src_tmp.GlyphsSet.Create(src_tmp.GlyphsHighest + 1); - if (dst_tmp.GlyphsSet.Storage.empty()) - dst_tmp.GlyphsSet.Create(dst_tmp.GlyphsHighest + 1); - - for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) - for (unsigned int codepoint = src_range[0]; codepoint <= src_range[1]; codepoint++) - { - if (dst_tmp.GlyphsSet.TestBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option for MergeMode (e.g. MergeOverwrite==true) - continue; - if (!stbtt_FindGlyphIndex(&src_tmp.FontInfo, codepoint)) // It is actually in the font? - continue; - - // Add to avail set/counters - src_tmp.GlyphsCount++; - dst_tmp.GlyphsCount++; - src_tmp.GlyphsSet.SetBit(codepoint); - dst_tmp.GlyphsSet.SetBit(codepoint); - total_glyphs_count++; - } - } - - // 3. Unpack our bit map into a flat list (we now have all the Unicode points that we know are requested _and_ available _and_ not overlapping another) - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; - src_tmp.GlyphsList.reserve(src_tmp.GlyphsCount); - UnpackBitVectorToFlatIndexList(&src_tmp.GlyphsSet, &src_tmp.GlyphsList); - src_tmp.GlyphsSet.Clear(); - IM_ASSERT(src_tmp.GlyphsList.Size == src_tmp.GlyphsCount); - } - for (int dst_i = 0; dst_i < dst_tmp_array.Size; dst_i++) - dst_tmp_array[dst_i].GlyphsSet.Clear(); - dst_tmp_array.clear(); - - // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0) - // (We technically don't need to zero-clear buf_rects, but let's do it for the sake of sanity) - ImVector buf_rects; - ImVector buf_packedchars; - buf_rects.resize(total_glyphs_count); - buf_packedchars.resize(total_glyphs_count); - memset(buf_rects.Data, 0, (size_t)buf_rects.size_in_bytes()); - memset(buf_packedchars.Data, 0, (size_t)buf_packedchars.size_in_bytes()); - - // 4. Gather glyphs sizes so we can pack them in our virtual canvas. - int total_surface = 0; - int buf_rects_out_n = 0; - int buf_packedchars_out_n = 0; - const int pack_padding = atlas->TexGlyphPadding; - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; - if (src_tmp.GlyphsCount == 0) - continue; - - src_tmp.Rects = &buf_rects[buf_rects_out_n]; - src_tmp.PackedChars = &buf_packedchars[buf_packedchars_out_n]; - buf_rects_out_n += src_tmp.GlyphsCount; - buf_packedchars_out_n += src_tmp.GlyphsCount; - - // Automatic selection of oversampling parameters - ImFontConfig& src = atlas->Sources[src_i]; - int oversample_h, oversample_v; - ImFontAtlasBuildGetOversampleFactors(&src, &oversample_h, &oversample_v); - - // Convert our ranges in the format stb_truetype wants - src_tmp.PackRange.font_size = src.SizePixels * src.RasterizerDensity; - src_tmp.PackRange.first_unicode_codepoint_in_range = 0; - src_tmp.PackRange.array_of_unicode_codepoints = src_tmp.GlyphsList.Data; - src_tmp.PackRange.num_chars = src_tmp.GlyphsList.Size; - src_tmp.PackRange.chardata_for_range = src_tmp.PackedChars; - src_tmp.PackRange.h_oversample = (unsigned char)oversample_h; - src_tmp.PackRange.v_oversample = (unsigned char)oversample_v; - - // Gather the sizes of all rectangles we will need to pack (this loop is based on stbtt_PackFontRangesGatherRects) - const float scale = (src.SizePixels > 0.0f) ? stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, src.SizePixels * src.RasterizerDensity) : stbtt_ScaleForMappingEmToPixels(&src_tmp.FontInfo, -src.SizePixels * src.RasterizerDensity); - for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++) - { - int x0, y0, x1, y1; - const int glyph_index_in_font = stbtt_FindGlyphIndex(&src_tmp.FontInfo, src_tmp.GlyphsList[glyph_i]); - IM_ASSERT(glyph_index_in_font != 0); - stbtt_GetGlyphBitmapBoxSubpixel(&src_tmp.FontInfo, glyph_index_in_font, scale * oversample_h, scale * oversample_v, 0, 0, &x0, &y0, &x1, &y1); - src_tmp.Rects[glyph_i].w = (stbrp_coord)(x1 - x0 + pack_padding + oversample_h - 1); - src_tmp.Rects[glyph_i].h = (stbrp_coord)(y1 - y0 + pack_padding + oversample_v - 1); - total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h; + const ImWchar* ranges = src->GlyphRanges ? src->GlyphRanges : atlas->GetGlyphRangesDefault(); + for (; ranges[0]; ranges += 2) + for (unsigned int c = ranges[0]; c <= ranges[1] && c <= IM_UNICODE_CODEPOINT_MAX; c++) //-V560 + baked->FindGlyph((ImWchar)c); } } - for (int i = 0; i < atlas->CustomRects.Size; i++) - total_surface += (atlas->CustomRects[i].Width + pack_padding) * (atlas->CustomRects[i].Height + pack_padding); - - // We need a width for the skyline algorithm, any width! - // The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height. - // User can override TexDesiredWidth and TexGlyphPadding if they wish, otherwise we use a simple heuristic to select the width based on expected surface. - const int surface_sqrt = (int)ImSqrt((float)total_surface) + 1; - atlas->TexHeight = 0; - if (atlas->TexDesiredWidth > 0) - atlas->TexWidth = atlas->TexDesiredWidth; - else - atlas->TexWidth = (surface_sqrt >= 4096 * 0.7f) ? 4096 : (surface_sqrt >= 2048 * 0.7f) ? 2048 : (surface_sqrt >= 1024 * 0.7f) ? 1024 : 512; - - // 5. Start packing - // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). - const int TEX_HEIGHT_MAX = 1024 * 32; - stbtt_pack_context spc = {}; - stbtt_PackBegin(&spc, NULL, atlas->TexWidth, TEX_HEIGHT_MAX, 0, 0, NULL); - spc.padding = atlas->TexGlyphPadding; // Because we mixup stbtt_PackXXX and stbrp_PackXXX there's a bit of a hack here, not passing the value to stbtt_PackBegin() allows us to still pack a TexWidth-1 wide item. (#8107) - ImFontAtlasBuildPackCustomRects(atlas, spc.pack_info); - - // 6. Pack each source font. No rendering yet, we are working with rectangles in an infinitely tall texture at this point. - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; - if (src_tmp.GlyphsCount == 0) - continue; - - stbrp_pack_rects((stbrp_context*)spc.pack_info, src_tmp.Rects, src_tmp.GlyphsCount); - - // Extend texture height and mark missing glyphs as non-packed so we won't render them. - // FIXME: We are not handling packing failure here (would happen if we got off TEX_HEIGHT_MAX or if a single if larger than TexWidth?) - for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++) - if (src_tmp.Rects[glyph_i].was_packed) - atlas->TexHeight = ImMax(atlas->TexHeight, src_tmp.Rects[glyph_i].y + src_tmp.Rects[glyph_i].h); - } - - // 7. Allocate texture - atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight); - atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight); - atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(atlas->TexWidth * atlas->TexHeight); - memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight); - spc.pixels = atlas->TexPixelsAlpha8; - spc.height = atlas->TexHeight; - - // 8. Render/rasterize font characters into the texture - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontConfig& src = atlas->Sources[src_i]; - ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; - if (src_tmp.GlyphsCount == 0) - continue; - - stbtt_PackFontRangesRenderIntoRects(&spc, &src_tmp.FontInfo, &src_tmp.PackRange, 1, src_tmp.Rects); - - // Apply multiply operator - if (src.RasterizerMultiply != 1.0f) - { - unsigned char multiply_table[256]; - ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, src.RasterizerMultiply); - stbrp_rect* r = &src_tmp.Rects[0]; - for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++, r++) - if (r->was_packed) - ImFontAtlasBuildMultiplyRectAlpha8(multiply_table, atlas->TexPixelsAlpha8, r->x, r->y, r->w, r->h, atlas->TexWidth * 1); - } - src_tmp.Rects = NULL; - } - - // End packing - stbtt_PackEnd(&spc); - buf_rects.clear(); - - // 9. Setup ImFont and glyphs for runtime - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - // When merging fonts with MergeMode=true: - // - We can have multiple input fonts writing into a same destination font. - // - dst_font->Sources is != from src which is our source configuration. - ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; - ImFontConfig& src = atlas->Sources[src_i]; - ImFont* dst_font = src.DstFont; - - const float font_scale = stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, src.SizePixels); - int unscaled_ascent, unscaled_descent, unscaled_line_gap; - stbtt_GetFontVMetrics(&src_tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); - - const float ascent = ImCeil(unscaled_ascent * font_scale); - const float descent = ImFloor(unscaled_descent * font_scale); - ImFontAtlasBuildSetupFont(atlas, dst_font, &src, ascent, descent); - const float font_off_x = src.GlyphOffset.x; - const float font_off_y = src.GlyphOffset.y + IM_ROUND(dst_font->Ascent); - - const float inv_rasterization_scale = 1.0f / src.RasterizerDensity; - - for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++) - { - // Register glyph - const int codepoint = src_tmp.GlyphsList[glyph_i]; - const stbtt_packedchar& pc = src_tmp.PackedChars[glyph_i]; - stbtt_aligned_quad q; - float unused_x = 0.0f, unused_y = 0.0f; - stbtt_GetPackedQuad(src_tmp.PackedChars, atlas->TexWidth, atlas->TexHeight, glyph_i, &unused_x, &unused_y, &q, 0); - float x0 = q.x0 * inv_rasterization_scale + font_off_x; - float y0 = q.y0 * inv_rasterization_scale + font_off_y; - float x1 = q.x1 * inv_rasterization_scale + font_off_x; - float y1 = q.y1 * inv_rasterization_scale + font_off_y; - dst_font->AddGlyph(&src, (ImWchar)codepoint, x0, y0, x1, y1, q.s0, q.t0, q.s1, q.t1, pc.xadvance * inv_rasterization_scale); - } - } - - // Cleanup - src_tmp_array.clear_destruct(); - - ImFontAtlasBuildFinish(atlas); - return true; } -const ImFontBuilderIO* ImFontAtlasGetBuilderForStbTruetype() -{ - static ImFontBuilderIO io; - io.FontBuilder_Build = ImFontAtlasBuildWithStbTruetype; - return &io; -} - -#endif // IMGUI_ENABLE_STB_TRUETYPE - -void ImFontAtlasUpdateSourcesPointers(ImFontAtlas* atlas) +// FIXME: May make ImFont::Sources a ImSpan<> and move ownership to ImFontAtlas +void ImFontAtlasBuildUpdatePointers(ImFontAtlas* atlas) { + for (ImFont* font : atlas->Fonts) + font->Sources.resize(0); for (ImFontConfig& src : atlas->Sources) + src.DstFont->Sources.push_back(&src); +} + +// Render a white-colored bitmap encoded in a string +void ImFontAtlasBuildRenderBitmapFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char) +{ + ImTextureData* tex = atlas->TexData; + IM_ASSERT(x >= 0 && x + w <= tex->Width); + IM_ASSERT(y >= 0 && y + h <= tex->Height); + + switch (tex->Format) { - ImFont* font = src.DstFont; - if (!src.MergeMode) - { - font->Sources = &src; - font->SourcesCount = 0; - } - font->SourcesCount++; + case ImTextureFormat_Alpha8: + { + ImU8* out_p = (ImU8*)tex->GetPixelsAt(x, y); + for (int off_y = 0; off_y < h; off_y++, out_p += tex->Width, in_str += w) + for (int off_x = 0; off_x < w; off_x++) + out_p[off_x] = (in_str[off_x] == in_marker_char) ? 0xFF : 0x00; + break; + } + case ImTextureFormat_RGBA32: + { + ImU32* out_p = (ImU32*)tex->GetPixelsAt(x, y); + for (int off_y = 0; off_y < h; off_y++, out_p += tex->Width, in_str += w) + for (int off_x = 0; off_x < w; off_x++) + out_p[off_x] = (in_str[off_x] == in_marker_char) ? IM_COL32_WHITE : IM_COL32_BLACK_TRANS; + break; + } } } -void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent) +static void ImFontAtlasBuildUpdateBasicTexData(ImFontAtlas* atlas) { - if (!font_config->MergeMode) + // Pack and store identifier so we can refresh UV coordinates on texture resize. + // FIXME-NEWATLAS: User/custom rects where user code wants to store UV coordinates will need to do the same thing. + ImFontAtlasBuilder* builder = atlas->Builder; + ImVec2i pack_size = (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) ? ImVec2i(2, 2) : ImVec2i(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); + + ImFontAtlasRect r; + bool add_and_draw = (atlas->GetCustomRect(builder->PackIdMouseCursors, &r) == false); + if (add_and_draw) { - font->ClearOutputData(); - font->FontSize = font_config->SizePixels; - IM_ASSERT(font->Sources == font_config); - font->ContainerAtlas = atlas; - font->Ascent = ascent; - font->Descent = descent; - } -} + builder->PackIdMouseCursors = atlas->AddCustomRect(pack_size.x, pack_size.y, &r); + IM_ASSERT(builder->PackIdMouseCursors != ImFontAtlasRectId_Invalid); -void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque) -{ - stbrp_context* pack_context = (stbrp_context*)stbrp_context_opaque; - IM_ASSERT(pack_context != NULL); - - ImVector& user_rects = atlas->CustomRects; - IM_ASSERT(user_rects.Size >= 1); // We expect at least the default custom rects to be registered, else something went wrong. -#ifdef __GNUC__ - if (user_rects.Size < 1) { __builtin_unreachable(); } // Workaround for GCC bug if IM_ASSERT() is defined to conditionally throw (see #5343) -#endif - - const int pack_padding = atlas->TexGlyphPadding; - ImVector pack_rects; - pack_rects.resize(user_rects.Size); - memset(pack_rects.Data, 0, (size_t)pack_rects.size_in_bytes()); - for (int i = 0; i < user_rects.Size; i++) - { - pack_rects[i].w = user_rects[i].Width + pack_padding; - pack_rects[i].h = user_rects[i].Height + pack_padding; - } - stbrp_pack_rects(pack_context, &pack_rects[0], pack_rects.Size); - for (int i = 0; i < pack_rects.Size; i++) - if (pack_rects[i].was_packed) + // Draw to texture + if (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) { - user_rects[i].X = (unsigned short)pack_rects[i].x; - user_rects[i].Y = (unsigned short)pack_rects[i].y; - IM_ASSERT(pack_rects[i].w == user_rects[i].Width + pack_padding && pack_rects[i].h == user_rects[i].Height + pack_padding); - atlas->TexHeight = ImMax(atlas->TexHeight, pack_rects[i].y + pack_rects[i].h); - } -} - -void ImFontAtlasBuildRender8bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned char in_marker_pixel_value) -{ - IM_ASSERT(x >= 0 && x + w <= atlas->TexWidth); - IM_ASSERT(y >= 0 && y + h <= atlas->TexHeight); - unsigned char* out_pixel = atlas->TexPixelsAlpha8 + x + (y * atlas->TexWidth); - for (int off_y = 0; off_y < h; off_y++, out_pixel += atlas->TexWidth, in_str += w) - for (int off_x = 0; off_x < w; off_x++) - out_pixel[off_x] = (in_str[off_x] == in_marker_char) ? in_marker_pixel_value : 0x00; -} - -void ImFontAtlasBuildRender32bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned int in_marker_pixel_value) -{ - IM_ASSERT(x >= 0 && x + w <= atlas->TexWidth); - IM_ASSERT(y >= 0 && y + h <= atlas->TexHeight); - unsigned int* out_pixel = atlas->TexPixelsRGBA32 + x + (y * atlas->TexWidth); - for (int off_y = 0; off_y < h; off_y++, out_pixel += atlas->TexWidth, in_str += w) - for (int off_x = 0; off_x < w; off_x++) - out_pixel[off_x] = (in_str[off_x] == in_marker_char) ? in_marker_pixel_value : IM_COL32_BLACK_TRANS; -} - -static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) -{ - ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdMouseCursors); - IM_ASSERT(r->IsPacked()); - - const int w = atlas->TexWidth; - if (atlas->Flags & ImFontAtlasFlags_NoMouseCursors) - { - // White pixels only - IM_ASSERT(r->Width == 2 && r->Height == 2); - const int offset = (int)r->X + (int)r->Y * w; - if (atlas->TexPixelsAlpha8 != NULL) - { - atlas->TexPixelsAlpha8[offset] = atlas->TexPixelsAlpha8[offset + 1] = atlas->TexPixelsAlpha8[offset + w] = atlas->TexPixelsAlpha8[offset + w + 1] = 0xFF; + // 2x2 white pixels + ImFontAtlasBuildRenderBitmapFromString(atlas, r.x, r.y, 2, 2, "XX" "XX", 'X'); } else { - atlas->TexPixelsRGBA32[offset] = atlas->TexPixelsRGBA32[offset + 1] = atlas->TexPixelsRGBA32[offset + w] = atlas->TexPixelsRGBA32[offset + w + 1] = IM_COL32_WHITE; + // 2x2 white pixels + mouse cursors + const int x_for_white = r.x; + const int x_for_black = r.x + FONT_ATLAS_DEFAULT_TEX_DATA_W + 1; + ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_white, r.y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.'); + ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_black, r.y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X'); } } - else - { - // White pixels and mouse cursor - IM_ASSERT(r->Width == FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1 && r->Height == FONT_ATLAS_DEFAULT_TEX_DATA_H); - const int x_for_white = r->X; - const int x_for_black = r->X + FONT_ATLAS_DEFAULT_TEX_DATA_W + 1; - if (atlas->TexPixelsAlpha8 != NULL) - { - ImFontAtlasBuildRender8bppRectFromString(atlas, x_for_white, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.', 0xFF); - ImFontAtlasBuildRender8bppRectFromString(atlas, x_for_black, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X', 0xFF); - } - else - { - ImFontAtlasBuildRender32bppRectFromString(atlas, x_for_white, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.', IM_COL32_WHITE); - ImFontAtlasBuildRender32bppRectFromString(atlas, x_for_black, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X', IM_COL32_WHITE); - } - } - atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y); + + // Refresh UV coordinates + atlas->TexUvWhitePixel = ImVec2((r.x + 0.5f) * atlas->TexUvScale.x, (r.y + 0.5f) * atlas->TexUvScale.y); } -static void ImFontAtlasBuildRenderLinesTexData(ImFontAtlas* atlas) +static void ImFontAtlasBuildUpdateLinesTexData(ImFontAtlas* atlas) { if (atlas->Flags & ImFontAtlasFlags_NoBakedLines) return; + // Pack and store identifier so we can refresh UV coordinates on texture resize. + ImTextureData* tex = atlas->TexData; + ImFontAtlasBuilder* builder = atlas->Builder; + + ImFontAtlasRect r; + bool add_and_draw = atlas->GetCustomRect(builder->PackIdLinesTexData, &r) == false; + if (add_and_draw) + { + ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); + builder->PackIdLinesTexData = atlas->AddCustomRect(pack_size.x, pack_size.y, &r); + IM_ASSERT(builder->PackIdLinesTexData != ImFontAtlasRectId_Invalid); + } + + // Register texture region for thick lines + // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them - ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdLines); - IM_ASSERT(r->IsPacked()); for (int n = 0; n < IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row { // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle - int y = n; - int line_width = n; - int pad_left = (r->Width - line_width) / 2; - int pad_right = r->Width - (pad_left + line_width); + const int y = n; + const int line_width = n; + const int pad_left = (r.w - line_width) / 2; + const int pad_right = r.w - (pad_left + line_width); + IM_ASSERT(pad_left + line_width + pad_right == r.w && y < r.h); // Make sure we're inside the texture bounds before we start writing pixels // Write each slice - IM_ASSERT(pad_left + line_width + pad_right == r->Width && y < r->Height); // Make sure we're inside the texture bounds before we start writing pixels - if (atlas->TexPixelsAlpha8 != NULL) + if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) { - unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r->X + ((r->Y + y) * atlas->TexWidth)]; + ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y + y); for (int i = 0; i < pad_left; i++) *(write_ptr + i) = 0x00; @@ -4076,9 +4334,9 @@ static void ImFontAtlasBuildRenderLinesTexData(ImFontAtlas* atlas) for (int i = 0; i < pad_right; i++) *(write_ptr + pad_left + line_width + i) = 0x00; } - else + else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32) { - unsigned int* write_ptr = &atlas->TexPixelsRGBA32[r->X + ((r->Y + y) * atlas->TexWidth)]; + ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r.x, r.y + y); for (int i = 0; i < pad_left; i++) *(write_ptr + i) = IM_COL32(255, 255, 255, 0); @@ -4089,28 +4347,616 @@ static void ImFontAtlasBuildRenderLinesTexData(ImFontAtlas* atlas) *(write_ptr + pad_left + line_width + i) = IM_COL32(255, 255, 255, 0); } - // Calculate UVs for this line - ImVec2 uv0 = ImVec2((float)(r->X + pad_left - 1), (float)(r->Y + y)) * atlas->TexUvScale; - ImVec2 uv1 = ImVec2((float)(r->X + pad_left + line_width + 1), (float)(r->Y + y + 1)) * atlas->TexUvScale; + // Refresh UV coordinates + ImVec2 uv0 = ImVec2((float)(r.x + pad_left - 1), (float)(r.y + y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(r.x + pad_left + line_width + 1), (float)(r.y + y + 1)) * atlas->TexUvScale; float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } } -// Register the rectangles we need for the rounded corner images -static void ImFontAtlasBuildRegisterShadowCustomRects(ImFontAtlas* atlas) +static void ImFontAtlasBuildUpdateShadowTexData(ImFontAtlas* atlas); // FIXME-SHADOWS: Move impl here. + +//----------------------------------------------------------------------------------------------------------------------------- + +// Was tempted to lazily init FontSrc but wouldn't save much + makes it more complicated to detect invalid data at AddFont() +bool ImFontAtlasFontInitOutput(ImFontAtlas* atlas, ImFont* font) { - if (atlas->ShadowRectIds[0] >= 0) + bool ret = true; + for (ImFontConfig* src : font->Sources) + if (!ImFontAtlasFontSourceInit(atlas, src)) + ret = false; + IM_ASSERT(ret); // Unclear how to react to this meaningfully. Assume that result will be same as initial AddFont() call. + return ret; +} + +// Keep source/input FontData +void ImFontAtlasFontDestroyOutput(ImFontAtlas* atlas, ImFont* font) +{ + font->ClearOutputData(); + for (ImFontConfig* src : font->Sources) + { + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader && loader->FontSrcDestroy != NULL) + loader->FontSrcDestroy(atlas, src); + } +} + +//----------------------------------------------------------------------------------------------------------------------------- + +bool ImFontAtlasFontSourceInit(ImFontAtlas* atlas, ImFontConfig* src) +{ + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader->FontSrcInit != NULL && !loader->FontSrcInit(atlas, src)) + return false; + return true; +} + +void ImFontAtlasFontSourceAddToFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src) +{ + if (src->MergeMode == false) + { + font->ClearOutputData(); + //font->FontSize = src->SizePixels; + font->ContainerAtlas = atlas; + IM_ASSERT(font->Sources[0] == src); + } + atlas->TexIsBuilt = false; // For legacy backends + ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src); +} + +void ImFontAtlasFontDestroySourceData(ImFontAtlas* atlas, ImFontConfig* src) +{ + IM_UNUSED(atlas); + if (src->FontDataOwnedByAtlas) + IM_FREE(src->FontData); + src->FontData = NULL; + if (src->GlyphExcludeRanges) + IM_FREE((void*)src->GlyphExcludeRanges); + src->GlyphExcludeRanges = NULL; +} + +// Create a compact, baked "..." if it doesn't exist, by using the ".". +// This may seem overly complicated right now but the point is to exercise and improve a technique which should be increasingly used. +// FIXME-NEWATLAS: This borrows too much from FontLoader's FontLoadGlyph() handlers and suggest that we should add further helpers. +static ImFontGlyph* ImFontAtlasBuildSetupFontBakedEllipsis(ImFontAtlas* atlas, ImFontBaked* baked) +{ + ImFont* font = baked->ContainerFont; + IM_ASSERT(font->EllipsisChar != 0); + + const ImFontGlyph* dot_glyph = baked->FindGlyphNoFallback((ImWchar)'.'); + if (dot_glyph == NULL) + dot_glyph = baked->FindGlyphNoFallback((ImWchar)0xFF0E); + if (dot_glyph == NULL) + return NULL; + ImFontAtlasRectId dot_r_id = dot_glyph->PackId; // Deep copy to avoid invalidation of glyphs and rect pointers + ImTextureRect* dot_r = ImFontAtlasPackGetRect(atlas, dot_r_id); + const int dot_spacing = 1; + const float dot_step = (dot_glyph->X1 - dot_glyph->X0) + dot_spacing; + + ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, (dot_r->w * 3 + dot_spacing * 2), dot_r->h); + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id); + + ImFontGlyph glyph_in = {}; + ImFontGlyph* glyph = &glyph_in; + glyph->Codepoint = font->EllipsisChar; + glyph->AdvanceX = ImMax(dot_glyph->AdvanceX, dot_glyph->X0 + dot_step * 3.0f - dot_spacing); // FIXME: Slightly odd for normally mono-space fonts but since this is used for trailing contents. + glyph->X0 = dot_glyph->X0; + glyph->Y0 = dot_glyph->Y0; + glyph->X1 = dot_glyph->X0 + dot_step * 3 - dot_spacing; + glyph->Y1 = dot_glyph->Y1; + glyph->Visible = true; + glyph->PackId = pack_id; + glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, NULL, glyph); + dot_glyph = NULL; // Invalidated + + // Copy to texture, post-process and queue update for backend + // FIXME-NEWATLAS-V2: Dot glyph is already post-processed as this point, so this would damage it. + dot_r = ImFontAtlasPackGetRect(atlas, dot_r_id); + ImTextureData* tex = atlas->TexData; + for (int n = 0; n < 3; n++) + ImFontAtlasTextureBlockCopy(tex, dot_r->x, dot_r->y, tex, r->x + (dot_r->w + dot_spacing) * n, r->y, dot_r->w, dot_r->h); + ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); + + return glyph; +} + +// Load fallback in order to obtain its index +// (this is called from in hot-path so we avoid extraneous parameters to minimize impact on code size) +static void ImFontAtlasBuildSetupFontBakedFallback(ImFontBaked* baked) +{ + IM_ASSERT(baked->FallbackGlyphIndex == -1); + IM_ASSERT(baked->FallbackAdvanceX == 0.0f); + ImFont* font = baked->ContainerFont; + ImFontGlyph* fallback_glyph = NULL; + if (font->FallbackChar != 0) + fallback_glyph = baked->FindGlyphNoFallback(font->FallbackChar); + if (fallback_glyph == NULL) + { + ImFontGlyph* space_glyph = baked->FindGlyphNoFallback((ImWchar)' '); + ImFontGlyph glyph; + glyph.Codepoint = 0; + glyph.AdvanceX = space_glyph ? space_glyph->AdvanceX : IM_ROUND(baked->Size * 0.40f); + fallback_glyph = ImFontAtlasBakedAddFontGlyph(font->ContainerAtlas, baked, NULL, &glyph); + } + baked->FallbackGlyphIndex = baked->Glyphs.index_from_ptr(fallback_glyph); // Storing index avoid need to update pointer on growth and simplify inner loop code + baked->FallbackAdvanceX = fallback_glyph->AdvanceX; +} + +static void ImFontAtlasBuildSetupFontBakedBlanks(ImFontAtlas* atlas, ImFontBaked* baked) +{ + // Mark space as always hidden (not strictly correct/necessary. but some e.g. icons fonts don't have a space. it tends to look neater in previews) + ImFontGlyph* space_glyph = baked->FindGlyphNoFallback((ImWchar)' '); + if (space_glyph != NULL) + space_glyph->Visible = false; + + // Setup Tab character. + // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) + if (baked->FindGlyphNoFallback('\t') == NULL && space_glyph != NULL) + { + ImFontGlyph tab_glyph; + tab_glyph.Codepoint = '\t'; + tab_glyph.AdvanceX = space_glyph->AdvanceX * IM_TABSIZE; + ImFontAtlasBakedAddFontGlyph(atlas, baked, NULL, &tab_glyph); + } +} + +// Load/identify special glyphs +// (note that this is called again for fonts with MergeMode) +void ImFontAtlasBuildSetupFontSpecialGlyphs(ImFontAtlas* atlas, ImFont* font, ImFontConfig* src) +{ + IM_UNUSED(atlas); + IM_ASSERT(font->Sources.contains(src)); + + // Find Fallback character. Actual glyph loaded in GetFontBaked(). + const ImWchar fallback_chars[] = { font->FallbackChar, (ImWchar)IM_UNICODE_CODEPOINT_INVALID, (ImWchar)'?', (ImWchar)' ' }; + if (font->FallbackChar == 0) + for (ImWchar candidate_char : fallback_chars) + if (candidate_char != 0 && font->IsGlyphInFont(candidate_char)) + { + font->FallbackChar = (ImWchar)candidate_char; + break; + } + + // Setup Ellipsis character. It is required for rendering elided text. We prefer using U+2026 (horizontal ellipsis). + // However some old fonts may contain ellipsis at U+0085. Here we auto-detect most suitable ellipsis character. + // FIXME: Note that 0x2026 is rarely included in our font ranges. Because of this we are more likely to use three individual dots. + const ImWchar ellipsis_chars[] = { src->EllipsisChar, (ImWchar)0x2026, (ImWchar)0x0085 }; + if (font->EllipsisChar == 0) + for (ImWchar candidate_char : ellipsis_chars) + if (candidate_char != 0 && font->IsGlyphInFont(candidate_char)) + { + font->EllipsisChar = candidate_char; + break; + } + if (font->EllipsisChar == 0) + { + font->EllipsisChar = 0x0085; + font->EllipsisAutoBake = true; + } +} + +void ImFontAtlasBakedDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph) +{ + if (glyph->PackId != ImFontAtlasRectId_Invalid) + { + ImFontAtlasPackDiscardRect(atlas, glyph->PackId); + glyph->PackId = ImFontAtlasRectId_Invalid; + } + ImWchar c = (ImWchar)glyph->Codepoint; + IM_ASSERT(font->FallbackChar != c && font->EllipsisChar != c); // Unsupported for simplicity + IM_ASSERT(glyph >= baked->Glyphs.Data && glyph < baked->Glyphs.Data + baked->Glyphs.Size); + IM_UNUSED(font); + baked->IndexLookup[c] = IM_FONTGLYPH_INDEX_UNUSED; + baked->IndexAdvanceX[c] = baked->FallbackAdvanceX; +} + +ImFontBaked* ImFontAtlasBakedAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density, ImGuiID baked_id) +{ + IMGUI_DEBUG_LOG_FONT("[font] Created baked %.2fpx\n", font_size); + ImFontBaked* baked = atlas->Builder->BakedPool.push_back(ImFontBaked()); + baked->Size = font_size; + baked->RasterizerDensity = font_rasterizer_density; + baked->BakedId = baked_id; + baked->ContainerFont = font; + baked->LastUsedFrame = atlas->Builder->FrameCount; + + // Initialize backend data + size_t loader_data_size = 0; + for (ImFontConfig* src : font->Sources) // Cannot easily be cached as we allow changing backend + { + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + loader_data_size += loader->FontBakedSrcLoaderDataSize; + } + baked->FontLoaderDatas = (loader_data_size > 0) ? IM_ALLOC(loader_data_size) : NULL; + char* loader_data_p = (char*)baked->FontLoaderDatas; + for (ImFontConfig* src : font->Sources) + { + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader->FontBakedInit) + loader->FontBakedInit(atlas, src, baked, loader_data_p); + loader_data_p += loader->FontBakedSrcLoaderDataSize; + } + + ImFontAtlasBuildSetupFontBakedBlanks(atlas, baked); + return baked; +} + +// FIXME-OPT: This is not a fast query. Adding a BakedCount field in Font might allow to take a shortcut for the most common case. +ImFontBaked* ImFontAtlasBakedGetClosestMatch(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density) +{ + ImFontAtlasBuilder* builder = atlas->Builder; + for (int step_n = 0; step_n < 2; step_n++) + { + ImFontBaked* closest_larger_match = NULL; + ImFontBaked* closest_smaller_match = NULL; + for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + { + ImFontBaked* baked = &builder->BakedPool[baked_n]; + if (baked->ContainerFont != font || baked->WantDestroy) + continue; + if (step_n == 0 && baked->RasterizerDensity != font_rasterizer_density) // First try with same density + continue; + if (baked->Size > font_size && (closest_larger_match == NULL || baked->Size < closest_larger_match->Size)) + closest_larger_match = baked; + if (baked->Size < font_size && (closest_smaller_match == NULL || baked->Size > closest_smaller_match->Size)) + closest_smaller_match = baked; + } + if (closest_larger_match) + if (closest_smaller_match == NULL || (closest_larger_match->Size >= font_size * 2.0f && closest_smaller_match->Size > font_size * 0.5f)) + return closest_larger_match; + if (closest_smaller_match) + return closest_smaller_match; + } + return NULL; +} + +void ImFontAtlasBakedDiscard(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked) +{ + ImFontAtlasBuilder* builder = atlas->Builder; + IMGUI_DEBUG_LOG_FONT("[font] Discard baked %.2f for \"%s\"\n", baked->Size, font->GetDebugName()); + + for (ImFontGlyph& glyph : baked->Glyphs) + if (glyph.PackId != ImFontAtlasRectId_Invalid) + ImFontAtlasPackDiscardRect(atlas, glyph.PackId); + + char* loader_data_p = (char*)baked->FontLoaderDatas; + for (ImFontConfig* src : font->Sources) + { + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader->FontBakedDestroy) + loader->FontBakedDestroy(atlas, src, baked, loader_data_p); + loader_data_p += loader->FontBakedSrcLoaderDataSize; + } + if (baked->FontLoaderDatas) + { + IM_FREE(baked->FontLoaderDatas); + baked->FontLoaderDatas = NULL; + } + builder->BakedMap.SetVoidPtr(baked->BakedId, NULL); + builder->BakedDiscardedCount++; + baked->ClearOutputData(); + baked->WantDestroy = true; + font->LastBaked = NULL; +} + +// use unused_frames==0 to discard everything. +void ImFontAtlasFontDiscardBakes(ImFontAtlas* atlas, ImFont* font, int unused_frames) +{ + if (ImFontAtlasBuilder* builder = atlas->Builder) // This can be called from font destructor + for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + { + ImFontBaked* baked = &builder->BakedPool[baked_n]; + if (baked->LastUsedFrame + unused_frames > atlas->Builder->FrameCount) + continue; + if (baked->ContainerFont != font || baked->WantDestroy) + continue; + ImFontAtlasBakedDiscard(atlas, font, baked); + } +} + +// use unused_frames==0 to discard everything. +void ImFontAtlasBuildDiscardBakes(ImFontAtlas* atlas, int unused_frames) +{ + ImFontAtlasBuilder* builder = atlas->Builder; + for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + { + ImFontBaked* baked = &builder->BakedPool[baked_n]; + if (baked->LastUsedFrame + unused_frames > atlas->Builder->FrameCount) + continue; + if (baked->WantDestroy || (baked->ContainerFont->Flags & ImFontFlags_LockBakedSizes)) + continue; + ImFontAtlasBakedDiscard(atlas, baked->ContainerFont, baked); + } +} + +// Those functions are designed to facilitate changing the underlying structures for ImFontAtlas to store an array of ImDrawListSharedData* +void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data) +{ + IM_ASSERT(!atlas->DrawListSharedDatas.contains(data)); + atlas->DrawListSharedDatas.push_back(data); +} + +void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data) +{ + IM_ASSERT(atlas->DrawListSharedDatas.contains(data)); + atlas->DrawListSharedDatas.find_erase(data); +} + +// Update texture identifier in all active draw lists +void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex, ImTextureRef new_tex) +{ + for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) + for (ImDrawList* draw_list : shared_data->DrawLists) + { + // Replace in command-buffer + // (there is not need to replace in ImDrawListSplitter: current channel is in ImDrawList's CmdBuffer[], + // other channels will be on SetCurrentChannel() which already needs to compare CmdHeader anyhow) + if (draw_list->CmdBuffer.Size > 0 && draw_list->_CmdHeader.TexRef == old_tex) + draw_list->_SetTexture(new_tex); + + // Replace in stack + for (ImTextureRef& stacked_tex : draw_list->_TextureStack) + if (stacked_tex == old_tex) + stacked_tex = new_tex; + } +} + +// Update texture coordinates in all draw list shared context +// FIXME-NEWATLAS FIXME-OPT: Doesn't seem necessary to update for all, only one bound to current context? +void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas) +{ + for (ImDrawListSharedData* shared_data : atlas->DrawListSharedDatas) + if (shared_data->FontAtlas == atlas) + { + shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel; + shared_data->TexUvLines = atlas->TexUvLines; + } +} + +// Set current texture. This is mostly called from AddTexture() + to handle a failed resize. +static void ImFontAtlasBuildSetTexture(ImFontAtlas* atlas, ImTextureData* tex) +{ + ImTextureRef old_tex_ref = atlas->TexRef; + atlas->TexData = tex; + atlas->TexUvScale = ImVec2(1.0f / tex->Width, 1.0f / tex->Height); + atlas->TexRef._TexData = tex; + //atlas->TexRef._TexID = tex->TexID; // <-- We intentionally don't do that. It would be misleading and betray promise that both fields aren't set. + ImFontAtlasUpdateDrawListsTextures(atlas, old_tex_ref, atlas->TexRef); +} + +// Create a new texture, discard previous one +ImTextureData* ImFontAtlasTextureAdd(ImFontAtlas* atlas, int w, int h) +{ + ImTextureData* old_tex = atlas->TexData; + ImTextureData* new_tex; + + // FIXME: Cannot reuse texture because old UV may have been used already (unless we remap UV). + /*if (old_tex != NULL && old_tex->Status == ImTextureStatus_WantCreate) + { + // Reuse texture not yet used by backend. + IM_ASSERT(old_tex->TexID == ImTextureID_Invalid && old_tex->BackendUserData == NULL); + old_tex->DestroyPixels(); + old_tex->Updates.clear(); + new_tex = old_tex; + old_tex = NULL; + } + else*/ + { + // Add new + new_tex = IM_NEW(ImTextureData)(); + new_tex->UniqueID = atlas->TexNextUniqueID++; + atlas->TexList.push_back(new_tex); + } + if (old_tex != NULL) + { + // Queue old as to destroy next frame + old_tex->WantDestroyNextFrame = true; + IM_ASSERT(old_tex->Status == ImTextureStatus_OK || old_tex->Status == ImTextureStatus_WantCreate || old_tex->Status == ImTextureStatus_WantUpdates); + } + + new_tex->Create(atlas->TexDesiredFormat, w, h); + new_tex->Status = ImTextureStatus_WantCreate; + atlas->TexIsBuilt = false; + + ImFontAtlasBuildSetTexture(atlas, new_tex); + + return new_tex; +} + +#if 0 +#define STB_IMAGE_WRITE_IMPLEMENTATION +#include "../stb/stb_image_write.h" +static void ImFontAtlasDebugWriteTexToDisk(ImTextureData* tex, const char* description) +{ + ImGuiContext& g = *GImGui; + char buf[128]; + ImFormatString(buf, IM_ARRAYSIZE(buf), "[%05d] Texture #%03d - %s.png", g.FrameCount, tex->UniqueID, description); + stbi_write_png(buf, tex->Width, tex->Height, tex->BytesPerPixel, tex->Pixels, tex->GetPitch()); // tex->BytesPerPixel is technically not component, but ok for the formats we support. +} +#endif + +void ImFontAtlasTextureRepack(ImFontAtlas* atlas, int w, int h) +{ + ImFontAtlasBuilder* builder = atlas->Builder; + builder->LockDisableResize = true; + + ImTextureData* old_tex = atlas->TexData; + ImTextureData* new_tex = ImFontAtlasTextureAdd(atlas, w, h); + new_tex->UseColors = old_tex->UseColors; + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize+repack %dx%d => Texture #%03d: %dx%d\n", old_tex->UniqueID, old_tex->Width, old_tex->Height, new_tex->UniqueID, new_tex->Width, new_tex->Height); + //for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + // IMGUI_DEBUG_LOG_FONT("[font] - Baked %.2fpx, %d glyphs, want_destroy=%d\n", builder->BakedPool[baked_n].FontSize, builder->BakedPool[baked_n].Glyphs.Size, builder->BakedPool[baked_n].WantDestroy); + //IMGUI_DEBUG_LOG_FONT("[font] - Old packed rects: %d, area %d px\n", builder->RectsPackedCount, builder->RectsPackedSurface); + //ImFontAtlasDebugWriteTexToDisk(old_tex, "Before Pack"); + + // Repack, lose discarded rectangle, copy pixels + // FIXME-NEWATLAS: This is unstable because packing order is based on RectsIndex + // FIXME-NEWATLAS-V2: Repacking in batch would be beneficial to packing heuristic, and fix stability. + // FIXME-NEWATLAS-TESTS: Test calling RepackTexture with size too small to fits existing rects. + ImFontAtlasPackInit(atlas); + ImVector old_rects; + ImVector old_index = builder->RectsIndex; + old_rects.swap(builder->Rects); + + for (ImFontAtlasRectEntry& index_entry : builder->RectsIndex) + { + if (index_entry.IsUsed == false) + continue; + ImTextureRect& old_r = old_rects[index_entry.TargetIndex]; + if (old_r.w == 0 && old_r.h == 0) + continue; + ImFontAtlasRectId new_r_id = ImFontAtlasPackAddRect(atlas, old_r.w, old_r.h, &index_entry); + if (new_r_id == ImFontAtlasRectId_Invalid) + { + // Undo, grow texture and try repacking again. + // FIXME-NEWATLAS-TESTS: This is a very rarely exercised path! It needs to be automatically tested properly. + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize failed. Will grow.\n", new_tex->UniqueID); + new_tex->WantDestroyNextFrame = true; + builder->Rects.swap(old_rects); + builder->RectsIndex = old_index; + ImFontAtlasBuildSetTexture(atlas, old_tex); + ImFontAtlasTextureGrow(atlas, w, h); // Recurse + return; + } + IM_ASSERT(ImFontAtlasRectId_GetIndex(new_r_id) == builder->RectsIndex.index_from_ptr(&index_entry)); + ImTextureRect* new_r = ImFontAtlasPackGetRect(atlas, new_r_id); + ImFontAtlasTextureBlockCopy(old_tex, old_r.x, old_r.y, new_tex, new_r->x, new_r->y, new_r->w, new_r->h); + } + IM_ASSERT(old_rects.Size == builder->Rects.Size + builder->RectsDiscardedCount); + builder->RectsDiscardedCount = 0; + builder->RectsDiscardedSurface = 0; + + // Patch glyphs UV + for (int baked_n = 0; baked_n < builder->BakedPool.Size; baked_n++) + for (ImFontGlyph& glyph : builder->BakedPool[baked_n].Glyphs) + if (glyph.PackId != ImFontAtlasRectId_Invalid) + { + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, glyph.PackId); + glyph.U0 = (r->x) * atlas->TexUvScale.x; + glyph.V0 = (r->y) * atlas->TexUvScale.y; + glyph.U1 = (r->x + r->w) * atlas->TexUvScale.x; + glyph.V1 = (r->y + r->h) * atlas->TexUvScale.y; + } + + // Update other cached UV + ImFontAtlasBuildUpdateLinesTexData(atlas); + ImFontAtlasBuildUpdateBasicTexData(atlas); + ImFontAtlasBuildUpdateShadowTexData(atlas); + + builder->LockDisableResize = false; + ImFontAtlasUpdateDrawListsSharedData(atlas); + //ImFontAtlasDebugWriteTexToDisk(new_tex, "After Pack"); +} + +void ImFontAtlasTextureGrow(ImFontAtlas* atlas, int old_tex_w, int old_tex_h) +{ + //ImFontAtlasDebugWriteTexToDisk(atlas->TexData, "Before Grow"); + ImFontAtlasBuilder* builder = atlas->Builder; + if (old_tex_w == -1) + old_tex_w = atlas->TexData->Width; + if (old_tex_h == -1) + old_tex_h = atlas->TexData->Height; + + // FIXME-NEWATLAS-V2: What to do when reaching limits exposed by backend? + // FIXME-NEWATLAS-V2: Does ImFontAtlasFlags_NoPowerOfTwoHeight makes sense now? Allow 'lock' and 'compact' operations? + IM_ASSERT(ImIsPowerOfTwo(old_tex_w) && ImIsPowerOfTwo(old_tex_h)); + IM_ASSERT(ImIsPowerOfTwo(atlas->TexMinWidth) && ImIsPowerOfTwo(atlas->TexMaxWidth) && ImIsPowerOfTwo(atlas->TexMinHeight) && ImIsPowerOfTwo(atlas->TexMaxHeight)); + + // Grow texture so it follows roughly a square. + // - Grow height before width, as width imply more packing nodes. + // - Caller should be taking account of RectsDiscardedSurface and may not need to grow. + int new_tex_w = (old_tex_h <= old_tex_w) ? old_tex_w : old_tex_w * 2; + int new_tex_h = (old_tex_h <= old_tex_w) ? old_tex_h * 2 : old_tex_h; + + // Handle minimum size first (for pathologically large packed rects) + const int pack_padding = atlas->TexGlyphPadding; + new_tex_w = ImMax(new_tex_w, ImUpperPowerOfTwo(builder->MaxRectSize.x + pack_padding)); + new_tex_h = ImMax(new_tex_h, ImUpperPowerOfTwo(builder->MaxRectSize.y + pack_padding)); + new_tex_w = ImClamp(new_tex_w, atlas->TexMinWidth, atlas->TexMaxWidth); + new_tex_h = ImClamp(new_tex_h, atlas->TexMinHeight, atlas->TexMaxHeight); + if (new_tex_w == old_tex_w && new_tex_h == old_tex_h) return; - // ShadowRectIds[0] is the rectangle for rectangular shadows - // ShadowRectIds[1] is the rectangle for convex shadows + ImFontAtlasTextureRepack(atlas, new_tex_w, new_tex_h); +} - // The actual size we want to reserve, including padding - const ImFontAtlasShadowTexConfig* shadow_cfg = &atlas->ShadowTexConfig; - const unsigned int effective_size = shadow_cfg->CalcRectTexSize() + shadow_cfg->GetRectTexPadding(); - atlas->ShadowRectIds[0] = atlas->AddCustomRectRegular(effective_size, effective_size); - atlas->ShadowRectIds[1] = atlas->AddCustomRectRegular(shadow_cfg->CalcConvexTexWidth() + shadow_cfg->GetConvexTexPadding(), shadow_cfg->CalcConvexTexHeight() + shadow_cfg->GetConvexTexPadding()); +void ImFontAtlasTextureMakeSpace(ImFontAtlas* atlas) +{ + // Can some baked contents be ditched? + //IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlasBuildMakeSpace()\n"); + ImFontAtlasBuilder* builder = atlas->Builder; + ImFontAtlasBuildDiscardBakes(atlas, 2); + + // Currently using a heuristic for repack without growing. + if (builder->RectsDiscardedSurface < builder->RectsPackedSurface * 0.20f) + ImFontAtlasTextureGrow(atlas); + else + ImFontAtlasTextureRepack(atlas, atlas->TexData->Width, atlas->TexData->Height); +} + +ImVec2i ImFontAtlasTextureGetSizeEstimate(ImFontAtlas* atlas) +{ + int min_w = ImUpperPowerOfTwo(atlas->TexMinWidth); + int min_h = ImUpperPowerOfTwo(atlas->TexMinHeight); + if (atlas->Builder == NULL || atlas->TexData == NULL || atlas->TexData->Status == ImTextureStatus_WantDestroy) + return ImVec2i(min_w, min_h); + + ImFontAtlasBuilder* builder = atlas->Builder; + min_w = ImMax(ImUpperPowerOfTwo(builder->MaxRectSize.x), min_w); + min_h = ImMax(ImUpperPowerOfTwo(builder->MaxRectSize.y), min_h); + const int surface_approx = builder->RectsPackedSurface - builder->RectsDiscardedSurface; // Expected surface after repack + const int surface_sqrt = (int)sqrtf((float)surface_approx); + + int new_tex_w; + int new_tex_h; + if (min_w >= min_h) + { + new_tex_w = ImMax(min_w, ImUpperPowerOfTwo(surface_sqrt)); + new_tex_h = ImMax(min_h, (int)((surface_approx + new_tex_w - 1) / new_tex_w)); + if ((atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) == 0) + new_tex_h = ImUpperPowerOfTwo(new_tex_h); + } + else + { + new_tex_h = ImMax(min_h, ImUpperPowerOfTwo(surface_sqrt)); + if ((atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) == 0) + new_tex_h = ImUpperPowerOfTwo(new_tex_h); + new_tex_w = ImMax(min_w, (int)((surface_approx + new_tex_h - 1) / new_tex_h)); + } + + IM_ASSERT(ImIsPowerOfTwo(new_tex_w) && ImIsPowerOfTwo(new_tex_h)); + return ImVec2i(new_tex_w, new_tex_h); +} + +// Clear all output. Invalidates all AddCustomRect() return values! +void ImFontAtlasBuildClear(ImFontAtlas* atlas) +{ + ImVec2i new_tex_size = ImFontAtlasTextureGetSizeEstimate(atlas); + ImFontAtlasBuildDestroy(atlas); + ImFontAtlasTextureAdd(atlas, new_tex_size.x, new_tex_size.y); + ImFontAtlasBuildInit(atlas); + for (ImFontConfig& src : atlas->Sources) + ImFontAtlasFontSourceInit(atlas, &src); + for (ImFont* font : atlas->Fonts) + for (ImFontConfig* src : font->Sources) + ImFontAtlasFontSourceAddToFont(atlas, font, src); +} + +// You should not need to call this manually! +// If you think you do, let us know and we can advise about policies auto-compact. +void ImFontAtlasTextureCompact(ImFontAtlas* atlas) +{ + ImFontAtlasBuilder* builder = atlas->Builder; + ImFontAtlasBuildDiscardBakes(atlas, 1); + + ImTextureData* old_tex = atlas->TexData; + ImVec2i old_tex_size = ImVec2i(old_tex->Width, old_tex->Height); + ImVec2i new_tex_size = ImFontAtlasTextureGetSizeEstimate(atlas); + if (builder->RectsDiscardedCount == 0 && new_tex_size.x == old_tex_size.x && new_tex_size.y == old_tex_size.y) + return; + + ImFontAtlasTextureRepack(atlas, new_tex_size.x, new_tex_size.y); } // Calculates the signed distance from sample_pos to the nearest point on the rectangle defined by rect_min->rect_max @@ -4170,32 +5016,37 @@ static void GaussianBlur(float* data, int size) } // Generate the actual pixel data for rounded corners in the atlas -static void ImFontAtlasBuildRenderShadowTexData(ImFontAtlas* atlas) +static void ImFontAtlasBuildUpdateShadowTexData(ImFontAtlas* atlas) { - IM_ASSERT(atlas->TexPixelsAlpha8 != NULL || atlas->TexPixelsRGBA32 != NULL); - IM_ASSERT(atlas->ShadowRectIds[0] >= 0 && atlas->ShadowRectIds[1] >= 0); + // The actual size we want to reserve, including padding + const ImFontAtlasShadowTexConfig* shadow_cfg = &atlas->ShadowTexConfig; + const unsigned int effective_size = shadow_cfg->CalcRectTexSize() + shadow_cfg->GetRectTexPadding(); + const int corner_size = shadow_cfg->TexCornerSize; + const int edge_size = shadow_cfg->TexEdgeSize; // Because of the blur, we have to generate the full 3x3 texture here, and then we chop that down to just the 2x2 section we need later. // 'size' correspond to the our 3x3 size, whereas 'shadow_tex_size' correspond to our 2x2 version where duplicate mirrored corners are not stored. - const ImFontAtlasShadowTexConfig* shadow_cfg = &atlas->ShadowTexConfig; // The rectangular shadow texture + ImFontAtlasRect r; + bool add_and_draw = (atlas->GetCustomRect(atlas->ShadowRectIds[0], &r) == false); + if (add_and_draw) { + atlas->ShadowRectIds[0] = atlas->AddCustomRect(effective_size, effective_size, &r); + IM_ASSERT(atlas->ShadowRectIds[0] != ImFontAtlasRectId_Invalid); + const int size = shadow_cfg->TexCornerSize + shadow_cfg->TexEdgeSize + shadow_cfg->TexCornerSize; - const int corner_size = shadow_cfg->TexCornerSize; - const int edge_size = shadow_cfg->TexEdgeSize; // The bounds of the rectangle we are generating the shadow from const ImVec2 shadow_rect_min((float)corner_size, (float)corner_size); const ImVec2 shadow_rect_max((float)(corner_size + edge_size), (float)(corner_size + edge_size)); // Remove the padding we added - ImFontAtlasCustomRect r = atlas->CustomRects[atlas->ShadowRectIds[0]]; const int padding = shadow_cfg->GetRectTexPadding(); - r.X += (unsigned short)padding; - r.Y += (unsigned short)padding; - r.Width -= (unsigned short)padding * 2; - r.Height -= (unsigned short)padding * 2; + r.x += (unsigned short)padding; + r.y += (unsigned short)padding; + r.w -= (unsigned short)padding * 2; + r.h -= (unsigned short)padding * 2; // Generate distance field // We draw the actual texture content by evaluating the distance field for the inner rectangle @@ -4214,56 +5065,84 @@ static void ImFontAtlasBuildRenderShadowTexData(ImFontAtlas* atlas) GaussianBlur(tex_data, size); // Copy to texture, truncating to the actual required texture size (the bottom/right of the source data is chopped off, as we don't need it - see below). The truncated size is essentially the top 2x2 of our data, plus a little bit of padding for sampling. - const int tex_w = atlas->TexWidth; + ImTextureData* tex = atlas->TexData; const int shadow_tex_size = shadow_cfg->CalcRectTexSize(); for (int y = 0; y < shadow_tex_size; y++) for (int x = 0; x < shadow_tex_size; x++) { - const unsigned int offset = (int)(r.X + x) + (int)(r.Y + y) * tex_w; const float alpha_f = tex_data[x + (y * size)]; const unsigned char alpha_8 = (unsigned char)(0xFF * alpha_f); - if (atlas->TexPixelsAlpha8) - atlas->TexPixelsAlpha8[offset] = alpha_8; - else - atlas->TexPixelsRGBA32[offset] = IM_COL32(255, 255, 255, alpha_8); - } - // Generate UVs for each of the nine sections, which are arranged in a 3x3 grid starting from 0 in the top-left and going across then down + // FIXME-SHADOWS: May be optimized. + switch (atlas->TexData->Format) + { + case ImTextureFormat_Alpha8: + { + ImU8* out_p = (ImU8*)(void*)tex->GetPixelsAt(r.x + x, r.y + y); + *out_p = alpha_8; + break; + } + case ImTextureFormat_RGBA32: + { + ImU32* out_p = (ImU32*)(void*)tex->GetPixelsAt(r.x + x, r.y + y); + *out_p = IM_COL32(255, 255, 255, alpha_8);; + break; + } + } + } + } + + // Refresh UV coordinates + // Generate UVs for each of the nine sections, which are arranged in a 3x3 grid starting from 0 in the top-left and going across then down + if (atlas->GetCustomRect(atlas->ShadowRectIds[0], &r)) + { + // Remove the padding we added + const int padding = shadow_cfg->GetRectTexPadding(); + r.x += (unsigned short)padding; + r.y += (unsigned short)padding; + r.w -= (unsigned short)padding * 2; + r.h -= (unsigned short)padding * 2; + for (int i = 0; i < 9; i++) { // The third row/column of the 3x3 grid are generated by flipping the appropriate chunks of the upper 2x2 grid. bool flip_h = false; // Do we need to flip the UVs horizontally? bool flip_v = false; // Do we need to flip the UVs vertically? - ImFontAtlasCustomRect sub_rect = r; + ImFontAtlasRect sub_rect = r; switch (i % 3) { - case 0: sub_rect.Width = (unsigned short)corner_size; break; - case 1: sub_rect.X += (unsigned short)corner_size; sub_rect.Width = (unsigned short)edge_size; break; - case 2: sub_rect.Width = (unsigned short)corner_size; flip_h = true; break; + case 0: sub_rect.w = (unsigned short)corner_size; break; + case 1: sub_rect.x += (unsigned short)corner_size; sub_rect.w = (unsigned short)edge_size; break; + case 2: sub_rect.w = (unsigned short)corner_size; flip_h = true; break; } switch (i / 3) { - case 0: sub_rect.Height = (unsigned short)corner_size; break; - case 1: sub_rect.Y += (unsigned short)corner_size; sub_rect.Height = (unsigned short)edge_size; break; - case 2: sub_rect.Height = (unsigned short)corner_size; flip_v = true; break; + case 0: sub_rect.h = (unsigned short)corner_size; break; + case 1: sub_rect.y += (unsigned short)corner_size; sub_rect.h = (unsigned short)edge_size; break; + case 2: sub_rect.h = (unsigned short)corner_size; flip_v = true; break; } - ImVec2 uv0, uv1; - atlas->CalcCustomRectUV(&sub_rect, &uv0, &uv1); + // FIXME-SHADOWS: caching UV !! + ImVec2 uv0 = ImVec2((float)(sub_rect.x), (float)(sub_rect.y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(sub_rect.x + sub_rect.w), (float)(sub_rect.y + sub_rect.h)) * atlas->TexUvScale; atlas->ShadowRectUvs[i] = ImVec4(flip_h ? uv1.x : uv0.x, flip_v ? uv1.y : uv0.y, flip_h ? uv0.x : uv1.x, flip_v ? uv0.y : uv1.y); } } // The convex shape shadow texture + add_and_draw = (atlas->GetCustomRect(atlas->ShadowRectIds[1], &r) == false); + if (add_and_draw) { + atlas->ShadowRectIds[1] = atlas->AddCustomRect(shadow_cfg->CalcConvexTexWidth() + shadow_cfg->GetConvexTexPadding(), shadow_cfg->CalcConvexTexHeight() + shadow_cfg->GetConvexTexPadding(), &r); + IM_ASSERT(atlas->ShadowRectIds[1] != ImFontAtlasRectId_Invalid); + const int size = shadow_cfg->TexCornerSize * 2; const int padding = shadow_cfg->GetConvexTexPadding(); // Generate distance field // We draw the actual texture content by evaluating the distance field for the distance from a center point - ImFontAtlasCustomRect r = atlas->CustomRects[atlas->ShadowRectIds[1]]; ImVec2 center_point(size * 0.5f, size * 0.5f); float* tex_data = (float*)alloca(size * size * sizeof(float)); for (int y = 0; y < size; y++) @@ -4287,7 +5166,7 @@ static void ImFontAtlasBuildRenderShadowTexData(ImFontAtlas* atlas) const int tex_width = shadow_cfg->CalcConvexTexWidth(); const int tex_height = shadow_cfg->CalcConvexTexHeight(); - const int tex_w = atlas->TexWidth; + ImTextureData* tex = atlas->TexData; for (int y = 0; y < tex_height; y++) for (int x = 0; x < tex_width; x++) { @@ -4295,86 +5174,609 @@ static void ImFontAtlasBuildRenderShadowTexData(ImFontAtlas* atlas) const int src_y = ImClamp(y - src_y_offset, 0, size - 1); const float alpha_f = tex_data[src_x + (src_y * size)]; const unsigned char alpha_8 = (unsigned char)(0xFF * alpha_f); - const unsigned int offset = (int)(r.X + x) + (int)(r.Y + y) * tex_w; - if (atlas->TexPixelsAlpha8) - atlas->TexPixelsAlpha8[offset] = alpha_8; - else - atlas->TexPixelsRGBA32[offset] = IM_COL32(255, 255, 255, alpha_8); + + // FIXME-SHADOWS: May be optimized. + switch (atlas->TexData->Format) + { + case ImTextureFormat_Alpha8: + { + ImU8* out_p = (ImU8*)(void*)tex->GetPixelsAt(r.x + x, r.y + y); + *out_p = alpha_8; + break; + } + case ImTextureFormat_RGBA32: + { + ImU32* out_p = (ImU32*)(void*)tex->GetPixelsAt(r.x + x, r.y + y); + *out_p = IM_COL32(255, 255, 255, alpha_8);; + break; + } + } } + } + // Refresh UV coordinates + if (atlas->GetCustomRect(atlas->ShadowRectIds[1], &r)) + { // Remove the padding we added - r.X += (unsigned short)padding; - r.Y += (unsigned short)padding; - r.Width = (unsigned short)(tex_width - (padding * 2)); - r.Height = (unsigned short)(tex_height - (padding * 2)); + const int padding = shadow_cfg->GetConvexTexPadding(); + const int tex_width = shadow_cfg->CalcConvexTexWidth(); + const int tex_height = shadow_cfg->CalcConvexTexHeight(); + r.x += (unsigned short)padding; + r.y += (unsigned short)padding; + r.w = (unsigned short)(tex_width - (padding * 2)); + r.h = (unsigned short)(tex_height - (padding * 2)); - // Generate UVs - ImVec2 uv0, uv1; - atlas->CalcCustomRectUV(&r, &uv0, &uv1); + ImVec2 uv0 = ImVec2((float)(r.x), (float)(r.y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(r.x + r.w), (float)(r.y + r.h)) * atlas->TexUvScale; atlas->ShadowRectUvs[9] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); } } -// Note: this is called / shared by both the stb_truetype and the FreeType builder +// Start packing over current empty texture void ImFontAtlasBuildInit(ImFontAtlas* atlas) { - // Register texture region for mouse cursors or standard white pixels - if (atlas->PackIdMouseCursors < 0) + // Select Backend + // - Note that we do not reassign to atlas->FontLoader, since it is likely to point to static data which + // may mess with some hot-reloading schemes. If you need to assign to this (for dynamic selection) AND are + // using a hot-reloading scheme that messes up static data, store your own instance of FontLoader somewhere + // and point to it instead of pointing directly to return value of the GetFontLoaderXXX functions. + if (atlas->FontLoader == NULL) { - if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) - atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); - else - atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(2, 2); +#ifdef IMGUI_ENABLE_FREETYPE + atlas->SetFontLoader(ImGuiFreeType::GetFontLoader()); +#elif defined(IMGUI_ENABLE_STB_TRUETYPE) + atlas->SetFontLoader(ImFontAtlasGetFontLoaderForStbTruetype()); +#else + IM_ASSERT(0); // Invalid Build function +#endif } - // Register texture region for thick lines - // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row - if (atlas->PackIdLines < 0) - { - if (!(atlas->Flags & ImFontAtlasFlags_NoBakedLines)) - atlas->PackIdLines = atlas->AddCustomRectRegular(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); - } + // Create initial texture size + if (atlas->TexData == NULL || atlas->TexData->Pixels == NULL) + ImFontAtlasTextureAdd(atlas, ImUpperPowerOfTwo(atlas->TexMinWidth), ImUpperPowerOfTwo(atlas->TexMinHeight)); - ImFontAtlasBuildRegisterShadowCustomRects(atlas); + atlas->Builder = IM_NEW(ImFontAtlasBuilder)(); + if (atlas->FontLoader->LoaderInit) + atlas->FontLoader->LoaderInit(atlas); + + ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); + + ImFontAtlasPackInit(atlas); + + // Add required texture data + ImFontAtlasBuildUpdateLinesTexData(atlas); + ImFontAtlasBuildUpdateBasicTexData(atlas); + ImFontAtlasBuildUpdateShadowTexData(atlas); + + // Register fonts + ImFontAtlasBuildUpdatePointers(atlas); + + // Update UV coordinates etc. stored in bound ImDrawListSharedData instance + ImFontAtlasUpdateDrawListsSharedData(atlas); + + //atlas->TexIsBuilt = true; } -// This is called/shared by both the stb_truetype and the FreeType builder. -void ImFontAtlasBuildFinish(ImFontAtlas* atlas) +// Destroy builder and all cached glyphs. Do not destroy actual fonts. +void ImFontAtlasBuildDestroy(ImFontAtlas* atlas) { - // Render into our custom data blocks - IM_ASSERT(atlas->TexPixelsAlpha8 != NULL || atlas->TexPixelsRGBA32 != NULL); - ImFontAtlasBuildRenderDefaultTexData(atlas); - ImFontAtlasBuildRenderLinesTexData(atlas); - ImFontAtlasBuildRenderShadowTexData(atlas); - - // Register custom rectangle glyphs - for (int i = 0; i < atlas->CustomRects.Size; i++) + for (ImFont* font : atlas->Fonts) + ImFontAtlasFontDestroyOutput(atlas, font); + if (atlas->Builder && atlas->FontLoader && atlas->FontLoader->LoaderShutdown) { - const ImFontAtlasCustomRect* r = &atlas->CustomRects[i]; - if (r->Font == NULL || r->GlyphID == 0) - continue; + atlas->FontLoader->LoaderShutdown(atlas); + IM_ASSERT(atlas->FontLoaderData == NULL); + } + IM_DELETE(atlas->Builder); + atlas->Builder = NULL; +} - // Will ignore ImFontConfig settings: GlyphMinAdvanceX, GlyphMinAdvanceY, PixelSnapH - IM_ASSERT(r->Font->ContainerAtlas == atlas); - ImVec2 uv0, uv1; - atlas->CalcCustomRectUV(r, &uv0, &uv1); - r->Font->AddGlyph(NULL, (ImWchar)r->GlyphID, r->GlyphOffset.x, r->GlyphOffset.y, r->GlyphOffset.x + r->Width, r->GlyphOffset.y + r->Height, uv0.x, uv0.y, uv1.x, uv1.y, r->GlyphAdvanceX); - if (r->GlyphColored) - r->Font->Glyphs.back().Colored = 1; +void ImFontAtlasPackInit(ImFontAtlas * atlas) +{ + ImTextureData* tex = atlas->TexData; + ImFontAtlasBuilder* builder = atlas->Builder; + + // In theory we could decide to reduce the number of nodes, e.g. halve them, and waste a little texture space, but it doesn't seem worth it. + const int pack_node_count = tex->Width / 2; + builder->PackNodes.resize(pack_node_count); + IM_STATIC_ASSERT(sizeof(stbrp_context) <= sizeof(stbrp_context_opaque)); + stbrp_init_target((stbrp_context*)(void*)&builder->PackContext, tex->Width, tex->Height, builder->PackNodes.Data, builder->PackNodes.Size); + builder->RectsPackedSurface = builder->RectsPackedCount = 0; + builder->MaxRectSize = ImVec2i(0, 0); + builder->MaxRectBounds = ImVec2i(0, 0); +} + +// This is essentially a free-list pattern, it may be nice to wrap it into a dedicated type. +static ImFontAtlasRectId ImFontAtlasPackAllocRectEntry(ImFontAtlas* atlas, int rect_idx) +{ + ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; + int index_idx; + ImFontAtlasRectEntry* index_entry; + if (builder->RectsIndexFreeListStart < 0) + { + builder->RectsIndex.resize(builder->RectsIndex.Size + 1); + index_idx = builder->RectsIndex.Size - 1; + index_entry = &builder->RectsIndex[index_idx]; + memset(index_entry, 0, sizeof(*index_entry)); + } + else + { + index_idx = builder->RectsIndexFreeListStart; + index_entry = &builder->RectsIndex[index_idx]; + IM_ASSERT(index_entry->IsUsed == false && index_entry->Generation > 0); // Generation is incremented during DiscardRect + builder->RectsIndexFreeListStart = index_entry->TargetIndex; + } + index_entry->TargetIndex = rect_idx; + index_entry->IsUsed = 1; + return ImFontAtlasRectId_Make(index_idx, index_entry->Generation); +} + +// Overwrite existing entry +static ImFontAtlasRectId ImFontAtlasPackReuseRectEntry(ImFontAtlas* atlas, ImFontAtlasRectEntry* index_entry) +{ + IM_ASSERT(index_entry->IsUsed); + index_entry->TargetIndex = atlas->Builder->Rects.Size - 1; + int index_idx = atlas->Builder->RectsIndex.index_from_ptr(index_entry); + return ImFontAtlasRectId_Make(index_idx, index_entry->Generation); +} + +// This is expected to be called in batches and followed by a repack +void ImFontAtlasPackDiscardRect(ImFontAtlas* atlas, ImFontAtlasRectId id) +{ + IM_ASSERT(id != ImFontAtlasRectId_Invalid); + + ImTextureRect* rect = ImFontAtlasPackGetRect(atlas, id); + if (rect == NULL) + return; + + ImFontAtlasBuilder* builder = atlas->Builder; + int index_idx = ImFontAtlasRectId_GetIndex(id); + ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[index_idx]; + IM_ASSERT(index_entry->IsUsed && index_entry->TargetIndex >= 0); + index_entry->IsUsed = false; + index_entry->TargetIndex = builder->RectsIndexFreeListStart; + index_entry->Generation++; + + const int pack_padding = atlas->TexGlyphPadding; + builder->RectsIndexFreeListStart = index_idx; + builder->RectsDiscardedCount++; + builder->RectsDiscardedSurface += (rect->w + pack_padding) * (rect->h + pack_padding); + rect->w = rect->h = 0; // Clear rectangle so it won't be packed again +} + +// Important: Calling this may recreate a new texture and therefore change atlas->TexData +// FIXME-NEWFONTS: Expose other glyph padding settings for custom alteration (e.g. drop shadows). See #7962 +ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry) +{ + IM_ASSERT(w > 0 && w <= 0xFFFF); + IM_ASSERT(h > 0 && h <= 0xFFFF); + + ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; + const int pack_padding = atlas->TexGlyphPadding; + builder->MaxRectSize.x = ImMax(builder->MaxRectSize.x, w); + builder->MaxRectSize.y = ImMax(builder->MaxRectSize.y, h); + + // Pack + ImTextureRect r = { 0, 0, (unsigned short)w, (unsigned short)h }; + for (int attempts_remaining = 3; attempts_remaining >= 0; attempts_remaining--) + { + // Try packing + stbrp_rect pack_r = {}; + pack_r.w = w + pack_padding; + pack_r.h = h + pack_padding; + stbrp_pack_rects((stbrp_context*)(void*)&builder->PackContext, &pack_r, 1); + r.x = (unsigned short)pack_r.x; + r.y = (unsigned short)pack_r.y; + if (pack_r.was_packed) + break; + + // If we ran out of attempts, return fallback + if (attempts_remaining == 0 || builder->LockDisableResize) + { + IMGUI_DEBUG_LOG_FONT("[font] Failed packing %dx%d rectangle. Returning fallback.\n", w, h); + return ImFontAtlasRectId_Invalid; + } + + // Resize or repack atlas! (this should be a rare event) + ImFontAtlasTextureMakeSpace(atlas); } - // Build all fonts lookup tables - for (ImFont* font : atlas->Fonts) - if (font->DirtyLookupTables) - font->BuildLookupTable(); + builder->MaxRectBounds.x = ImMax(builder->MaxRectBounds.x, r.x + r.w + pack_padding); + builder->MaxRectBounds.y = ImMax(builder->MaxRectBounds.y, r.y + r.h + pack_padding); + builder->RectsPackedCount++; + builder->RectsPackedSurface += (w + pack_padding) * (h + pack_padding); - atlas->TexReady = true; + builder->Rects.push_back(r); + if (overwrite_entry != NULL) + return ImFontAtlasPackReuseRectEntry(atlas, overwrite_entry); // Write into an existing entry instead of adding one (used during repack) + else + return ImFontAtlasPackAllocRectEntry(atlas, builder->Rects.Size - 1); } +// Generally for non-user facing functions: assert on invalid ID. +ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id) +{ + IM_ASSERT(id != ImFontAtlasRectId_Invalid); + int index_idx = ImFontAtlasRectId_GetIndex(id); + ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; + ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[index_idx]; + IM_ASSERT(index_entry->Generation == ImFontAtlasRectId_GetGeneration(id)); + IM_ASSERT(index_entry->IsUsed); + return &builder->Rects[index_entry->TargetIndex]; +} + +// For user-facing functions: return NULL on invalid ID. +// Important: return pointer is valid until next call to AddRect(), e.g. FindGlyph(), CalcTextSize() can all potentially invalidate previous pointers. +ImTextureRect* ImFontAtlasPackGetRectSafe(ImFontAtlas* atlas, ImFontAtlasRectId id) +{ + if (id == ImFontAtlasRectId_Invalid) + return NULL; + int index_idx = ImFontAtlasRectId_GetIndex(id); + if (atlas->Builder == NULL) + ImFontAtlasBuildInit(atlas); + ImFontAtlasBuilder* builder = (ImFontAtlasBuilder*)atlas->Builder; + if (index_idx >= builder->RectsIndex.Size) + return NULL; + ImFontAtlasRectEntry* index_entry = &builder->RectsIndex[index_idx]; + if (index_entry->Generation != ImFontAtlasRectId_GetGeneration(id) || !index_entry->IsUsed) + return NULL; + return &builder->Rects[index_entry->TargetIndex]; +} + +// Important! This assume by ImFontConfig::GlyphExcludeRanges[] is a SMALL ARRAY (e.g. <10 entries) +// Use "Input Glyphs Overlap Detection Tool" to display a list of glyphs provided by multiple sources in order to set this array up. +static bool ImFontAtlasBuildAcceptCodepointForSource(ImFontConfig* src, ImWchar codepoint) +{ + if (const ImWchar* exclude_list = src->GlyphExcludeRanges) + for (; exclude_list[0] != 0; exclude_list += 2) + if (codepoint >= exclude_list[0] && codepoint <= exclude_list[1]) + return false; + return true; +} + +static void ImFontBaked_BuildGrowIndex(ImFontBaked* baked, int new_size) +{ + IM_ASSERT(baked->IndexAdvanceX.Size == baked->IndexLookup.Size); + if (new_size <= baked->IndexLookup.Size) + return; + baked->IndexAdvanceX.resize(new_size, -1.0f); + baked->IndexLookup.resize(new_size, IM_FONTGLYPH_INDEX_UNUSED); +} + +static void ImFontAtlas_FontHookRemapCodepoint(ImFontAtlas* atlas, ImFont* font, ImWchar* c) +{ + IM_UNUSED(atlas); + if (font->RemapPairs.Data.Size != 0) + *c = (ImWchar)font->RemapPairs.GetInt((ImGuiID)*c, (int)*c); +} + +static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codepoint, float* only_load_advance_x) +{ + ImFont* font = baked->ContainerFont; + ImFontAtlas* atlas = font->ContainerAtlas; + if (atlas->Locked || (font->Flags & ImFontFlags_NoLoadGlyphs)) + { + // Lazily load fallback glyph + if (baked->FallbackGlyphIndex == -1 && baked->LockLoadingFallback == 0) + ImFontAtlasBuildSetupFontBakedFallback(baked); + return NULL; + } + + // User remapping hooks + ImWchar src_codepoint = codepoint; + ImFontAtlas_FontHookRemapCodepoint(atlas, font, &codepoint); + + //char utf8_buf[5]; + //IMGUI_DEBUG_LOG("[font] BuildLoadGlyph U+%04X (%s)\n", (unsigned int)codepoint, ImTextCharToUtf8(utf8_buf, (unsigned int)codepoint)); + + // Special hook + // FIXME-NEWATLAS: it would be nicer if this used a more standardized way of hooking + if (codepoint == font->EllipsisChar && font->EllipsisAutoBake) + if (ImFontGlyph* glyph = ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked)) + return glyph; + + // Call backend + char* loader_user_data_p = (char*)baked->FontLoaderDatas; + int src_n = 0; + for (ImFontConfig* src : font->Sources) + { + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (!src->GlyphExcludeRanges || ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) + { + if (only_load_advance_x == NULL) + { + ImFontGlyph glyph_buf; + if (loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, &glyph_buf, NULL)) + { + // FIXME: Add hooks for e.g. #7962 + glyph_buf.Codepoint = src_codepoint; + glyph_buf.SourceIdx = src_n; + return ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph_buf); + } + } + else + { + // Special mode but only loading glyphs metrics. Will rasterize and pack later. + if (loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, NULL, only_load_advance_x)) + { + ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, *only_load_advance_x); + return NULL; + } + } + } + loader_user_data_p += loader->FontBakedSrcLoaderDataSize; + src_n++; + } + + // Lazily load fallback glyph + if (baked->LockLoadingFallback) + return NULL; + if (baked->FallbackGlyphIndex == -1) + ImFontAtlasBuildSetupFontBakedFallback(baked); + + // Mark index as not found, so we don't attempt the search twice + ImFontBaked_BuildGrowIndex(baked, codepoint + 1); + baked->IndexAdvanceX[codepoint] = baked->FallbackAdvanceX; + baked->IndexLookup[codepoint] = IM_FONTGLYPH_INDEX_NOT_FOUND; + return NULL; +} + +static float ImFontBaked_BuildLoadGlyphAdvanceX(ImFontBaked* baked, ImWchar codepoint) +{ + if (baked->Size >= IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE) + { + // First load AdvanceX value used by CalcTextSize() API then load the rest when loaded by drawing API. + float only_advance_x = 0.0f; + ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(baked, (ImWchar)codepoint, &only_advance_x); + return glyph ? glyph->AdvanceX : only_advance_x; + } + else + { + ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(baked, (ImWchar)codepoint, NULL); + return glyph ? glyph->AdvanceX : baked->FallbackAdvanceX; + } +} + +// The point of this indirection is to not be inlined in debug mode in order to not bloat inner loop.b +IM_MSVC_RUNTIME_CHECKS_OFF +static float BuildLoadGlyphGetAdvanceOrFallback(ImFontBaked* baked, unsigned int codepoint) +{ + return ImFontBaked_BuildLoadGlyphAdvanceX(baked, (ImWchar)codepoint); +} +IM_MSVC_RUNTIME_CHECKS_RESTORE + +#ifndef IMGUI_DISABLE_DEBUG_TOOLS +void ImFontAtlasDebugLogTextureRequests(ImFontAtlas* atlas) +{ + // [DEBUG] Log texture update requests + ImGuiContext& g = *GImGui; + IM_UNUSED(g); + for (ImTextureData* tex : atlas->TexList) + { + if ((g.IO.BackendFlags & ImGuiBackendFlags_RendererHasTextures) == 0) + IM_ASSERT(tex->Updates.Size == 0); + if (tex->Status == ImTextureStatus_WantCreate) + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: create %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + else if (tex->Status == ImTextureStatus_WantDestroy) + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: destroy %dx%d, texid=0x%" IM_PRIX64 ", backend_data=%p\n", tex->UniqueID, tex->Width, tex->Height, tex->TexID, tex->BackendUserData); + else if (tex->Status == ImTextureStatus_WantUpdates) + { + IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update %d regions, texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, tex->Updates.Size, tex->TexID, (ImU64)(intptr_t)tex->BackendUserData); + for (const ImTextureRect& r : tex->Updates) + { + IM_UNUSED(r); + IM_ASSERT(r.x >= 0 && r.y >= 0); + IM_ASSERT(r.x + r.w <= tex->Width && r.y + r.h <= tex->Height); // In theory should subtract PackPadding but it's currently part of atlas and mid-frame change would wreck assert. + //IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: update (% 4d..%-4d)->(% 4d..%-4d), texid=0x%" IM_PRIX64 ", backend_data=0x%" IM_PRIX64 "\n", tex->UniqueID, r.x, r.y, r.x + r.w, r.y + r.h, tex->TexID, (ImU64)(intptr_t)tex->BackendUserData); + } + } + } +} +#endif + +//------------------------------------------------------------------------- +// [SECTION] ImFontAtlas: backend for stb_truetype +//------------------------------------------------------------------------- +// (imstb_truetype.h in included near the top of this file, when IMGUI_ENABLE_STB_TRUETYPE is set) +//------------------------------------------------------------------------- + +#ifdef IMGUI_ENABLE_STB_TRUETYPE + +// One for each ConfigData +struct ImGui_ImplStbTrueType_FontSrcData +{ + stbtt_fontinfo FontInfo; + float ScaleFactor; +}; + +static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src) +{ + IM_UNUSED(atlas); + + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = IM_NEW(ImGui_ImplStbTrueType_FontSrcData); + IM_ASSERT(src->FontLoaderData == NULL); + + // Initialize helper structure for font loading and verify that the TTF/OTF data is correct + const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)src->FontData, src->FontNo); + if (font_offset < 0) + { + IM_DELETE(bd_font_data); + IM_ASSERT_USER_ERROR(0, "stbtt_GetFontOffsetForIndex(): FontData is incorrect, or FontNo cannot be found."); + return false; + } + if (!stbtt_InitFont(&bd_font_data->FontInfo, (unsigned char*)src->FontData, font_offset)) + { + IM_DELETE(bd_font_data); + IM_ASSERT_USER_ERROR(0, "stbtt_InitFont(): failed to parse FontData. It is correct and complete? Check FontDataSize."); + return false; + } + src->FontLoaderData = bd_font_data; + + if (src->MergeMode && src->SizePixels == 0.0f) + src->SizePixels = src->DstFont->Sources[0]->SizePixels; + + if (src->SizePixels >= 0.0f) + bd_font_data->ScaleFactor = stbtt_ScaleForPixelHeight(&bd_font_data->FontInfo, 1.0f); + else + bd_font_data->ScaleFactor = stbtt_ScaleForMappingEmToPixels(&bd_font_data->FontInfo, 1.0f); + if (src->MergeMode && src->SizePixels != 0.0f) + bd_font_data->ScaleFactor *= src->SizePixels / src->DstFont->Sources[0]->SizePixels; // FIXME-NEWATLAS: Should tidy up that a bit + + return true; +} + +static void ImGui_ImplStbTrueType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) +{ + IM_UNUSED(atlas); + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; + IM_DELETE(bd_font_data); + src->FontLoaderData = NULL; +} + +static bool ImGui_ImplStbTrueType_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint) +{ + IM_UNUSED(atlas); + + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; + IM_ASSERT(bd_font_data != NULL); + + int glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); + return glyph_index != 0; +} + +static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*) +{ + IM_UNUSED(atlas); + + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; + if (src->MergeMode == false) + { + // FIXME-NEWFONTS: reevaluate how to use sizing metrics + // FIXME-NEWFONTS: make use of line gap value + float scale_for_layout = bd_font_data->ScaleFactor * baked->Size; + int unscaled_ascent, unscaled_descent, unscaled_line_gap; + stbtt_GetFontVMetrics(&bd_font_data->FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); + baked->Ascent = ImCeil(unscaled_ascent * scale_for_layout); + baked->Descent = ImFloor(unscaled_descent * scale_for_layout); + } + return true; +} + +static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x) +{ + // Search for first font which has the glyph + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; + IM_ASSERT(bd_font_data); + int glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); + if (glyph_index == 0) + return false; + + // Fonts unit to pixels + int oversample_h, oversample_v; + ImFontAtlasBuildGetOversampleFactors(src, baked, &oversample_h, &oversample_v); + const float scale_for_layout = bd_font_data->ScaleFactor * baked->Size; + const float rasterizer_density = src->RasterizerDensity * baked->RasterizerDensity; + const float scale_for_raster_x = bd_font_data->ScaleFactor * baked->Size * rasterizer_density * oversample_h; + const float scale_for_raster_y = bd_font_data->ScaleFactor * baked->Size * rasterizer_density * oversample_v; + + // Obtain size and advance + int x0, y0, x1, y1; + int advance, lsb; + stbtt_GetGlyphBitmapBoxSubpixel(&bd_font_data->FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y, 0, 0, &x0, &y0, &x1, &y1); + stbtt_GetGlyphHMetrics(&bd_font_data->FontInfo, glyph_index, &advance, &lsb); + + // Load metrics only mode + if (out_advance_x != NULL) + { + IM_ASSERT(out_glyph == NULL); + *out_advance_x = advance * scale_for_layout; + return true; + } + + // Prepare glyph + out_glyph->Codepoint = codepoint; + out_glyph->AdvanceX = advance * scale_for_layout; + + // Pack and retrieve position inside texture atlas + // (generally based on stbtt_PackFontRangesRenderIntoRects) + const bool is_visible = (x0 != x1 && y0 != y1); + if (is_visible) + { + const int w = (x1 - x0 + oversample_h - 1); + const int h = (y1 - y0 + oversample_v - 1); + ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, w, h); + if (pack_id == ImFontAtlasRectId_Invalid) + { + // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?) + IM_ASSERT(pack_id != ImFontAtlasRectId_Invalid && "Out of texture memory."); + return false; + } + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id); + + // Render + stbtt_GetGlyphBitmapBox(&bd_font_data->FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y, &x0, &y0, &x1, &y1); + ImFontAtlasBuilder* builder = atlas->Builder; + builder->TempBuffer.resize(w * h * 1); + unsigned char* bitmap_pixels = builder->TempBuffer.Data; + memset(bitmap_pixels, 0, w * h * 1); + stbtt_MakeGlyphBitmapSubpixel(&bd_font_data->FontInfo, bitmap_pixels, r->w - oversample_h + 1, r->h - oversample_v + 1, w, + scale_for_raster_x, scale_for_raster_y, 0, 0, glyph_index); + + // Oversampling + // (those functions conveniently assert if pixels are not cleared, which is another safety layer) + if (oversample_h > 1) + stbtt__h_prefilter(bitmap_pixels, r->w, r->h, r->w, oversample_h); + if (oversample_v > 1) + stbtt__v_prefilter(bitmap_pixels, r->w, r->h, r->w, oversample_v); + + const float ref_size = baked->ContainerFont->Sources[0]->SizePixels; + const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; + float font_off_x = (src->GlyphOffset.x * offsets_scale); + float font_off_y = (src->GlyphOffset.y * offsets_scale); + if (src->PixelSnapH) // Snap scaled offset. This is to mitigate backward compatibility issues for GlyphOffset, but a better design would be welcome. + font_off_x = IM_ROUND(font_off_x); + if (src->PixelSnapV) + font_off_y = IM_ROUND(font_off_y); + font_off_x += stbtt__oversample_shift(oversample_h); + font_off_y += stbtt__oversample_shift(oversample_v) + IM_ROUND(baked->Ascent); + float recip_h = 1.0f / (oversample_h * rasterizer_density); + float recip_v = 1.0f / (oversample_v * rasterizer_density); + + // Register glyph + // r->x r->y are coordinates inside texture (in pixels) + // glyph.X0, glyph.Y0 are drawing coordinates from base text position, and accounting for oversampling. + out_glyph->X0 = x0 * recip_h + font_off_x; + out_glyph->Y0 = y0 * recip_v + font_off_y; + out_glyph->X1 = (x0 + (int)r->w) * recip_h + font_off_x; + out_glyph->Y1 = (y0 + (int)r->h) * recip_v + font_off_y; + out_glyph->Visible = true; + out_glyph->PackId = pack_id; + ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, out_glyph, r, bitmap_pixels, ImTextureFormat_Alpha8, w); + } + + return true; +} + +const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype() +{ + static ImFontLoader loader; + loader.Name = "stb_truetype"; + loader.FontSrcInit = ImGui_ImplStbTrueType_FontSrcInit; + loader.FontSrcDestroy = ImGui_ImplStbTrueType_FontSrcDestroy; + loader.FontSrcContainsGlyph = ImGui_ImplStbTrueType_FontSrcContainsGlyph; + loader.FontBakedInit = ImGui_ImplStbTrueType_FontBakedInit; + loader.FontBakedDestroy = NULL; + loader.FontBakedLoadGlyph = ImGui_ImplStbTrueType_FontBakedLoadGlyph; + return &loader; +} + +#endif // IMGUI_ENABLE_STB_TRUETYPE + //------------------------------------------------------------------------- // [SECTION] ImFontAtlas: glyph ranges helpers //------------------------------------------------------------------------- // - GetGlyphRangesDefault() +// Obsolete functions since 1.92: // - GetGlyphRangesGreek() // - GetGlyphRangesKorean() // - GetGlyphRangesChineseFull() @@ -4396,6 +5798,7 @@ const ImWchar* ImFontAtlas::GetGlyphRangesDefault() return &ranges[0]; } +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS const ImWchar* ImFontAtlas::GetGlyphRangesGreek() { static const ImWchar ranges[] = @@ -4645,6 +6048,7 @@ const ImWchar* ImFontAtlas::GetGlyphRangesVietnamese() }; return &ranges[0]; } +#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS //----------------------------------------------------------------------------- // [SECTION] ImFontGlyphRangesBuilder @@ -4688,10 +6092,29 @@ void ImFontGlyphRangesBuilder::BuildRanges(ImVector* out_ranges) // [SECTION] ImFont //----------------------------------------------------------------------------- +ImFontBaked::ImFontBaked() +{ + memset(this, 0, sizeof(*this)); + FallbackGlyphIndex = -1; +} + +void ImFontBaked::ClearOutputData() +{ + FallbackAdvanceX = 0.0f; + Glyphs.clear(); + IndexAdvanceX.clear(); + IndexLookup.clear(); + FallbackGlyphIndex = -1; + Ascent = Descent = 0.0f; + MetricsTotalSurface = 0; +} + ImFont::ImFont() { memset(this, 0, sizeof(*this)); +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS Scale = 1.0f; +#endif } ImFont::~ImFont() @@ -4699,113 +6122,13 @@ ImFont::~ImFont() ClearOutputData(); } -void ImFont::ClearOutputData() +void ImFont::ClearOutputData() { - FontSize = 0.0f; - FallbackAdvanceX = 0.0f; - Glyphs.clear(); - IndexAdvanceX.clear(); - IndexLookup.clear(); - FallbackGlyph = NULL; - ContainerAtlas = NULL; - DirtyLookupTables = true; - Ascent = Descent = 0.0f; - MetricsTotalSurface = 0; + if (ImFontAtlas* atlas = ContainerAtlas) + ImFontAtlasFontDiscardBakes(atlas, this, 0); + FallbackChar = EllipsisChar = 0; memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); -} - -static ImWchar FindFirstExistingGlyph(ImFont* font, const ImWchar* candidate_chars, int candidate_chars_count) -{ - for (int n = 0; n < candidate_chars_count; n++) - if (font->FindGlyphNoFallback(candidate_chars[n]) != NULL) - return candidate_chars[n]; - return 0; -} - -void ImFont::BuildLookupTable() -{ - int max_codepoint = 0; - for (int i = 0; i != Glyphs.Size; i++) - max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint); - - // Build lookup table - IM_ASSERT(Glyphs.Size > 0 && "Font has not loaded glyph!"); - IM_ASSERT(Glyphs.Size < 0xFFFF); // -1 is reserved - IndexAdvanceX.clear(); - IndexLookup.clear(); - DirtyLookupTables = false; - memset(Used8kPagesMap, 0, sizeof(Used8kPagesMap)); - GrowIndex(max_codepoint + 1); - for (int i = 0; i < Glyphs.Size; i++) - { - int codepoint = (int)Glyphs[i].Codepoint; - IndexAdvanceX[codepoint] = Glyphs[i].AdvanceX; - IndexLookup[codepoint] = (ImU16)i; - - // Mark 4K page as used - const int page_n = codepoint / 8192; - Used8kPagesMap[page_n >> 3] |= 1 << (page_n & 7); - } - - // Create a glyph to handle TAB - // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) - if (FindGlyph((ImWchar)' ')) - { - if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times (FIXME: Flaky) - Glyphs.resize(Glyphs.Size + 1); - ImFontGlyph& tab_glyph = Glyphs.back(); - tab_glyph = *FindGlyph((ImWchar)' '); - tab_glyph.Codepoint = '\t'; - tab_glyph.AdvanceX *= IM_TABSIZE; - IndexAdvanceX[(int)tab_glyph.Codepoint] = (float)tab_glyph.AdvanceX; - IndexLookup[(int)tab_glyph.Codepoint] = (ImU16)(Glyphs.Size - 1); - } - - // Mark special glyphs as not visible (note that AddGlyph already mark as non-visible glyphs with zero-size polygons) - if (ImFontGlyph* glyph = (ImFontGlyph*)(void*)FindGlyph((ImWchar)' ')) - glyph->Visible = false; - if (ImFontGlyph* glyph = (ImFontGlyph*)(void*)FindGlyph((ImWchar)'\t')) - glyph->Visible = false; - - // Setup Fallback character - const ImWchar fallback_chars[] = { (ImWchar)IM_UNICODE_CODEPOINT_INVALID, (ImWchar)'?', (ImWchar)' ' }; - FallbackGlyph = FindGlyphNoFallback(FallbackChar); - if (FallbackGlyph == NULL) - { - FallbackChar = FindFirstExistingGlyph(this, fallback_chars, IM_ARRAYSIZE(fallback_chars)); - FallbackGlyph = FindGlyphNoFallback(FallbackChar); - if (FallbackGlyph == NULL) - { - FallbackGlyph = &Glyphs.back(); - FallbackChar = (ImWchar)FallbackGlyph->Codepoint; - } - } - FallbackAdvanceX = FallbackGlyph->AdvanceX; - for (int i = 0; i < max_codepoint + 1; i++) - if (IndexAdvanceX[i] < 0.0f) - IndexAdvanceX[i] = FallbackAdvanceX; - - // Setup Ellipsis character. It is required for rendering elided text. We prefer using U+2026 (horizontal ellipsis). - // However some old fonts may contain ellipsis at U+0085. Here we auto-detect most suitable ellipsis character. - // FIXME: Note that 0x2026 is rarely included in our font ranges. Because of this we are more likely to use three individual dots. - const ImWchar ellipsis_chars[] = { Sources->EllipsisChar, (ImWchar)0x2026, (ImWchar)0x0085 }; - const ImWchar dots_chars[] = { (ImWchar)'.', (ImWchar)0xFF0E }; - if (EllipsisChar == 0) - EllipsisChar = FindFirstExistingGlyph(this, ellipsis_chars, IM_ARRAYSIZE(ellipsis_chars)); - const ImWchar dot_char = FindFirstExistingGlyph(this, dots_chars, IM_ARRAYSIZE(dots_chars)); - if (EllipsisChar != 0) - { - EllipsisCharCount = 1; - EllipsisWidth = EllipsisCharStep = FindGlyph(EllipsisChar)->X1; - } - else if (dot_char != 0) - { - const ImFontGlyph* dot_glyph = FindGlyph(dot_char); - EllipsisChar = dot_char; - EllipsisCharCount = 3; - EllipsisCharStep = (float)(int)(dot_glyph->X1 - dot_glyph->X0) + 1.0f; - EllipsisWidth = ImMax(dot_glyph->AdvanceX, dot_glyph->X0 + EllipsisCharStep * 3.0f - 1.0f); // FIXME: Slightly odd for normally mono-space fonts but since this is used for trailing contents. - } + LastBaked = NULL; } // API is designed this way to avoid exposing the 8K page size @@ -4821,98 +6144,241 @@ bool ImFont::IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last) return true; } -void ImFont::GrowIndex(int new_size) -{ - IM_ASSERT(IndexAdvanceX.Size == IndexLookup.Size); - if (new_size <= IndexLookup.Size) - return; - IndexAdvanceX.resize(new_size, -1.0f); - IndexLookup.resize(new_size, (ImU16)-1); -} - // x0/y0/x1/y1 are offset from the character upper-left layout position, in pixels. Therefore x0/y0 are often fairly close to zero. // Not to be mistaken with texture coordinates, which are held by u0/v0/u1/v1 in normalized format (0.0..1.0 on each texture axis). -// 'src' is not necessarily == 'this->Sources' because multiple source fonts+configs can be used to build one target font. -void ImFont::AddGlyph(const ImFontConfig* src, ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x) +// - 'src' is not necessarily == 'this->Sources' because multiple source fonts+configs can be used to build one target font. +ImFontGlyph* ImFontAtlasBakedAddFontGlyph(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, const ImFontGlyph* in_glyph) { + int glyph_idx = baked->Glyphs.Size; + baked->Glyphs.push_back(*in_glyph); + ImFontGlyph* glyph = &baked->Glyphs[glyph_idx]; + IM_ASSERT(baked->Glyphs.Size < 0xFFFE); // IndexLookup[] hold 16-bit values and -1/-2 are reserved. + + // Set UV from packed rectangle + if (glyph->PackId != ImFontAtlasRectId_Invalid) + { + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, glyph->PackId); + IM_ASSERT(glyph->U0 == 0.0f && glyph->V0 == 0.0f && glyph->U1 == 0.0f && glyph->V1 == 0.0f); + glyph->U0 = (r->x) * atlas->TexUvScale.x; + glyph->V0 = (r->y) * atlas->TexUvScale.y; + glyph->U1 = (r->x + r->w) * atlas->TexUvScale.x; + glyph->V1 = (r->y + r->h) * atlas->TexUvScale.y; + baked->MetricsTotalSurface += r->w * r->h; + } + if (src != NULL) { // Clamp & recenter if needed - const float advance_x_original = advance_x; - advance_x = ImClamp(advance_x, src->GlyphMinAdvanceX, src->GlyphMaxAdvanceX); - if (advance_x != advance_x_original) + const float ref_size = baked->ContainerFont->Sources[0]->SizePixels; + const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; + float advance_x = ImClamp(glyph->AdvanceX, src->GlyphMinAdvanceX * offsets_scale, src->GlyphMaxAdvanceX * offsets_scale); + if (advance_x != glyph->AdvanceX) { - float char_off_x = src->PixelSnapH ? ImTrunc((advance_x - advance_x_original) * 0.5f) : (advance_x - advance_x_original) * 0.5f; - x0 += char_off_x; - x1 += char_off_x; + float char_off_x = src->PixelSnapH ? ImTrunc((advance_x - glyph->AdvanceX) * 0.5f) : (advance_x - glyph->AdvanceX) * 0.5f; + glyph->X0 += char_off_x; + glyph->X1 += char_off_x; } // Snap to pixel if (src->PixelSnapH) advance_x = IM_ROUND(advance_x); - // Bake extra spacing + // Bake spacing + glyph->AdvanceX = advance_x + src->GlyphExtraAdvanceX; + } + if (glyph->Colored) + atlas->TexPixelsUseColors = atlas->TexData->UseColors = true; + + // Update lookup tables + const int codepoint = glyph->Codepoint; + ImFontBaked_BuildGrowIndex(baked, codepoint + 1); + baked->IndexAdvanceX[codepoint] = glyph->AdvanceX; + baked->IndexLookup[codepoint] = (ImU16)glyph_idx; + const int page_n = codepoint / 8192; + baked->ContainerFont->Used8kPagesMap[page_n >> 3] |= 1 << (page_n & 7); + + return glyph; +} + +// FIXME: Code is duplicated with code above. +void ImFontAtlasBakedAddFontGlyphAdvancedX(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImWchar codepoint, float advance_x) +{ + IM_UNUSED(atlas); + if (src != NULL) + { + // Clamp & recenter if needed + const float ref_size = baked->ContainerFont->Sources[0]->SizePixels; + const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; + advance_x = ImClamp(advance_x, src->GlyphMinAdvanceX * offsets_scale, src->GlyphMaxAdvanceX * offsets_scale); + + // Snap to pixel + if (src->PixelSnapH) + advance_x = IM_ROUND(advance_x); + + // Bake spacing advance_x += src->GlyphExtraAdvanceX; } - int glyph_idx = Glyphs.Size; - Glyphs.resize(Glyphs.Size + 1); - ImFontGlyph& glyph = Glyphs[glyph_idx]; - glyph.Codepoint = (unsigned int)codepoint; - glyph.Visible = (x0 != x1) && (y0 != y1); - glyph.Colored = false; - glyph.X0 = x0; - glyph.Y0 = y0; - glyph.X1 = x1; - glyph.Y1 = y1; - glyph.U0 = u0; - glyph.V0 = v0; - glyph.U1 = u1; - glyph.V1 = v1; - glyph.AdvanceX = advance_x; - IM_ASSERT(Glyphs.Size < 0xFFFF); // IndexLookup[] hold 16-bit values and -1 is reserved. - - // Compute rough surface usage metrics (+1 to account for average padding, +0.99 to round) - // We use (U1-U0)*TexWidth instead of X1-X0 to account for oversampling. - float pad = ContainerAtlas->TexGlyphPadding + 0.99f; - DirtyLookupTables = true; - MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + pad) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + pad); + ImFontBaked_BuildGrowIndex(baked, codepoint + 1); + baked->IndexAdvanceX[codepoint] = advance_x; } -void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst) +// Copy to texture, post-process and queue update for backend +void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImTextureRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch) { - IM_ASSERT(IndexLookup.Size > 0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function. - unsigned int index_size = (unsigned int)IndexLookup.Size; - - if (dst < index_size && IndexLookup.Data[dst] == (ImU16)-1 && !overwrite_dst) // 'dst' already exists - return; - if (src >= index_size && dst >= index_size) // both 'dst' and 'src' don't exist -> no-op - return; - - GrowIndex(dst + 1); - IndexLookup[dst] = (src < index_size) ? IndexLookup.Data[src] : (ImU16)-1; - IndexAdvanceX[dst] = (src < index_size) ? IndexAdvanceX.Data[src] : 1.0f; + ImTextureData* tex = atlas->TexData; + IM_ASSERT(r->x + r->w <= tex->Width && r->y + r->h <= tex->Height); + ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, (unsigned char*)tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), r->w, r->h); + ImFontAtlasPostProcessData pp_data = { atlas, baked->ContainerFont, src, baked, glyph, tex->GetPixelsAt(r->x, r->y), tex->Format, tex->GetPitch(), r->w, r->h }; + ImFontAtlasTextureBlockPostProcess(&pp_data); + ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); } -// Find glyph, return fallback if missing -ImFontGlyph* ImFont::FindGlyph(ImWchar c) +void ImFont::AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint) { - if (c >= (size_t)IndexLookup.Size) - return FallbackGlyph; - const ImU16 i = IndexLookup.Data[c]; - if (i == (ImU16)-1) - return FallbackGlyph; - return &Glyphs.Data[i]; + RemapPairs.SetInt((ImGuiID)from_codepoint, (int)to_codepoint); } -ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c) +// Find glyph, load if necessary, return fallback if missing +ImFontGlyph* ImFontBaked::FindGlyph(ImWchar c) { - if (c >= (size_t)IndexLookup.Size) + if (c < (size_t)IndexLookup.Size) IM_LIKELY + { + const int i = (int)IndexLookup.Data[c]; + if (i == IM_FONTGLYPH_INDEX_NOT_FOUND) + return &Glyphs.Data[FallbackGlyphIndex]; + if (i != IM_FONTGLYPH_INDEX_UNUSED) + return &Glyphs.Data[i]; + } + ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(this, c, NULL); + return glyph ? glyph : &Glyphs.Data[FallbackGlyphIndex]; +} + +// Attempt to load but when missing, return NULL instead of FallbackGlyph +ImFontGlyph* ImFontBaked::FindGlyphNoFallback(ImWchar c) +{ + if (c < (size_t)IndexLookup.Size) IM_LIKELY + { + const int i = (int)IndexLookup.Data[c]; + if (i == IM_FONTGLYPH_INDEX_NOT_FOUND) + return NULL; + if (i != IM_FONTGLYPH_INDEX_UNUSED) + return &Glyphs.Data[i]; + } + LockLoadingFallback = true; // This is actually a rare call, not done in hot-loop, so we prioritize not adding extra cruft to ImFontBaked_BuildLoadGlyph() call sites. + ImFontGlyph* glyph = ImFontBaked_BuildLoadGlyph(this, c, NULL); + LockLoadingFallback = false; + return glyph; +} + +bool ImFontBaked::IsGlyphLoaded(ImWchar c) +{ + if (c < (size_t)IndexLookup.Size) IM_LIKELY + { + const int i = (int)IndexLookup.Data[c]; + if (i == IM_FONTGLYPH_INDEX_NOT_FOUND) + return false; + if (i != IM_FONTGLYPH_INDEX_UNUSED) + return true; + } + return false; +} + +// This is not fast query +bool ImFont::IsGlyphInFont(ImWchar c) +{ + ImFontAtlas* atlas = ContainerAtlas; + ImFontAtlas_FontHookRemapCodepoint(atlas, this, &c); + for (ImFontConfig* src : Sources) + { + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader->FontSrcContainsGlyph != NULL && loader->FontSrcContainsGlyph(atlas, src, c)) + return true; + } + return false; +} + +// This is manually inlined in CalcTextSizeA() and CalcWordWrapPosition(), with a non-inline call to BuildLoadGlyphGetAdvanceOrFallback(). +IM_MSVC_RUNTIME_CHECKS_OFF +float ImFontBaked::GetCharAdvance(ImWchar c) +{ + if ((int)c < IndexAdvanceX.Size) + { + // Missing glyphs fitting inside index will have stored FallbackAdvanceX already. + const float x = IndexAdvanceX.Data[c]; + if (x >= 0.0f) + return x; + } + return ImFontBaked_BuildLoadGlyphAdvanceX(this, c); +} +IM_MSVC_RUNTIME_CHECKS_RESTORE + +ImGuiID ImFontAtlasBakedGetId(ImGuiID font_id, float baked_size, float rasterizer_density) +{ + struct { ImGuiID FontId; float BakedSize; float RasterizerDensity; } hashed_data; + hashed_data.FontId = font_id; + hashed_data.BakedSize = baked_size; + hashed_data.RasterizerDensity = rasterizer_density; + return ImHashData(&hashed_data, sizeof(hashed_data)); +} + +// ImFontBaked pointers are valid for the entire frame but shall never be kept between frames. +ImFontBaked* ImFont::GetFontBaked(float size, float density) +{ + ImFontBaked* baked = LastBaked; + + // Round font size + // - ImGui::PushFont() will already round, but other paths calling GetFontBaked() directly also needs it (e.g. ImFontAtlasBuildPreloadAllGlyphRanges) + size = ImGui::GetRoundedFontSize(size); + + if (density < 0.0f) + density = CurrentRasterizerDensity; + if (baked && baked->Size == size && baked->RasterizerDensity == density) + return baked; + + ImFontAtlas* atlas = ContainerAtlas; + ImFontAtlasBuilder* builder = atlas->Builder; + baked = ImFontAtlasBakedGetOrAdd(atlas, this, size, density); + if (baked == NULL) return NULL; - const ImU16 i = IndexLookup.Data[c]; - if (i == (ImU16)-1) - return NULL; - return &Glyphs.Data[i]; + baked->LastUsedFrame = builder->FrameCount; + LastBaked = baked; + return baked; +} + +ImFontBaked* ImFontAtlasBakedGetOrAdd(ImFontAtlas* atlas, ImFont* font, float font_size, float font_rasterizer_density) +{ + // FIXME-NEWATLAS: Design for picking a nearest size based on some criteria? + // FIXME-NEWATLAS: Altering font density won't work right away. + IM_ASSERT(font_size > 0.0f && font_rasterizer_density > 0.0f); + ImGuiID baked_id = ImFontAtlasBakedGetId(font->FontId, font_size, font_rasterizer_density); + ImFontAtlasBuilder* builder = atlas->Builder; + ImFontBaked** p_baked_in_map = (ImFontBaked**)builder->BakedMap.GetVoidPtrRef(baked_id); + ImFontBaked* baked = *p_baked_in_map; + if (baked != NULL) + { + IM_ASSERT(baked->Size == font_size && baked->ContainerFont == font && baked->BakedId == baked_id); + return baked; + } + + // If atlas is locked, find closest match + // FIXME-OPT: This is not an optimal query. + if ((font->Flags & ImFontFlags_LockBakedSizes) || atlas->Locked) + { + baked = ImFontAtlasBakedGetClosestMatch(atlas, font, font_size, font_rasterizer_density); + if (baked != NULL) + return baked; + if (atlas->Locked) + { + IM_ASSERT(!atlas->Locked && "Cannot use dynamic font size with a locked ImFontAtlas!"); // Locked because rendering backend does not support ImGuiBackendFlags_RendererHasTextures! + return NULL; + } + } + + // Create new + baked = ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, baked_id); + *p_baked_in_map = baked; // To avoid 'builder->BakedMap.SetVoidPtr(baked_id, baked);' while we can. + return baked; } // Trim trailing space and find beginning of next line @@ -4925,12 +6391,10 @@ static inline const char* CalcWordWrapNextLineStartA(const char* text, const cha return text; } -#define ImFontGetCharAdvanceX(_FONT, _CH) ((int)(_CH) < (_FONT)->IndexAdvanceX.Size ? (_FONT)->IndexAdvanceX.Data[_CH] : (_FONT)->FallbackAdvanceX) - // Simple word-wrapping for English, not full-featured. Please submit failing cases! // This will return the next location to wrap from. If no wrapping if necessary, this will fast-forward to e.g. text_end. // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) -const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) +const char* ImFont::CalcWordWrapPosition(float size, const char* text, const char* text_end, float wrap_width) { // For references, possible wrap point marked with ^ // "aaa bbb, ccc,ddd. eee fff. ggg!" @@ -4943,6 +6407,10 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c // Cut words that cannot possibly fit within one line. // e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" + + ImFontBaked* baked = GetFontBaked(size); + const float scale = size / baked->Size; + float line_width = 0.0f; float word_width = 0.0f; float blank_width = 0.0f; @@ -4979,7 +6447,11 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c } } - const float char_width = ImFontGetCharAdvanceX(this, c); + // Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);' + float char_width = (c < (unsigned int)baked->IndexAdvanceX.Size) ? baked->IndexAdvanceX.Data[c] : -1.0f; + if (char_width < 0.0f) + char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c); + if (ImCharIsBlankW(c)) { if (inside_word) @@ -5006,7 +6478,7 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c } // Allow wrapping after punctuation. - inside_word = (c != '.' && c != ',' && c != ';' && c != '!' && c != '?' && c != '\"'); + inside_word = (c != '.' && c != ',' && c != ';' && c != '!' && c != '?' && c != '\"' && c != 0x3001 && c != 0x3002); } // We ignore blank width at the end of the line (they can be skipped) @@ -5024,7 +6496,7 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. // +1 may not be a character start point in UTF-8 but it's ok because caller loops use (text >= word_wrap_eol). if (s == text && text < text_end) - return s + 1; + return s + ImTextCountUtf8BytesFromChar(s, text_end); return s; } @@ -5034,7 +6506,8 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons text_end = text_begin + ImStrlen(text_begin); // FIXME-OPT: Need to avoid this. const float line_height = size; - const float scale = size / FontSize; + ImFontBaked* baked = GetFontBaked(size); + const float scale = size / baked->Size; ImVec2 text_size = ImVec2(0, 0); float line_width = 0.0f; @@ -5049,7 +6522,7 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons { // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. if (!word_wrap_eol) - word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width); + word_wrap_eol = CalcWordWrapPosition(size, s, text_end, wrap_width - line_width); if (s >= word_wrap_eol) { @@ -5084,7 +6557,12 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons continue; } - const float char_width = ImFontGetCharAdvanceX(this, c) * scale; + // Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);' + float char_width = (c < (unsigned int)baked->IndexAdvanceX.Size) ? baked->IndexAdvanceX.Data[c] : -1.0f; + if (char_width < 0.0f) + char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c); + char_width *= scale; + if (line_width + char_width >= max_width) { s = prev_s; @@ -5107,24 +6585,49 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons } // Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound. -void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c) +void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c, const ImVec4* cpu_fine_clip) { - const ImFontGlyph* glyph = FindGlyph(c); + ImFontBaked* baked = GetFontBaked(size); + const ImFontGlyph* glyph = baked->FindGlyph(c); if (!glyph || !glyph->Visible) return; if (glyph->Colored) col |= ~IM_COL32_A_MASK; - float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f; + float scale = (size >= 0.0f) ? (size / baked->Size) : 1.0f; float x = IM_TRUNC(pos.x); float y = IM_TRUNC(pos.y); + + float x1 = x + glyph->X0 * scale; + float x2 = x + glyph->X1 * scale; + if (cpu_fine_clip && (x1 > cpu_fine_clip->z || x2 < cpu_fine_clip->x)) + return; + float y1 = y + glyph->Y0 * scale; + float y2 = y + glyph->Y1 * scale; + float u1 = glyph->U0; + float v1 = glyph->V0; + float u2 = glyph->U1; + float v2 = glyph->V1; + + // Always CPU fine clip. Code extracted from RenderText(). + // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads. + if (cpu_fine_clip != NULL) + { + if (x1 < cpu_fine_clip->x) { u1 = u1 + (1.0f - (x2 - cpu_fine_clip->x) / (x2 - x1)) * (u2 - u1); x1 = cpu_fine_clip->x; } + if (y1 < cpu_fine_clip->y) { v1 = v1 + (1.0f - (y2 - cpu_fine_clip->y) / (y2 - y1)) * (v2 - v1); y1 = cpu_fine_clip->y; } + if (x2 > cpu_fine_clip->z) { u2 = u1 + ((cpu_fine_clip->z - x1) / (x2 - x1)) * (u2 - u1); x2 = cpu_fine_clip->z; } + if (y2 > cpu_fine_clip->w) { v2 = v1 + ((cpu_fine_clip->w - y1) / (y2 - y1)) * (v2 - v1); y2 = cpu_fine_clip->w; } + if (y1 >= y2) + return; + } draw_list->PrimReserve(6, 4); - draw_list->PrimRectUV(ImVec2(x + glyph->X0 * scale, y + glyph->Y0 * scale), ImVec2(x + glyph->X1 * scale, y + glyph->Y1 * scale), ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col); + draw_list->PrimRectUV(ImVec2(x1, y1), ImVec2(x2, y2), ImVec2(u1, v1), ImVec2(u2, v2), col); } // Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound. void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, bool cpu_fine_clip) { // Align to be pixel perfect +begin: float x = IM_TRUNC(pos.x); float y = IM_TRUNC(pos.y); if (y > clip_rect.w) @@ -5133,8 +6636,10 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im if (!text_end) text_end = text_begin + ImStrlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls. - const float scale = size / FontSize; - const float line_height = FontSize * scale; + const float line_height = size; + ImFontBaked* baked = GetFontBaked(size); + + const float scale = size / baked->Size; const float origin_x = x; const bool word_wrap_enabled = (wrap_width > 0.0f); @@ -5146,10 +6651,10 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im const char* line_end = (const char*)ImMemchr(s, '\n', text_end - s); if (word_wrap_enabled) { - // FIXME-OPT: This is not optimal as do first do a search for \n before calling CalcWordWrapPositionA(). - // If the specs for CalcWordWrapPositionA() were reworked to optionally return on \n we could combine both. + // FIXME-OPT: This is not optimal as do first do a search for \n before calling CalcWordWrapPosition(). + // If the specs for CalcWordWrapPosition() were reworked to optionally return on \n we could combine both. // However it is still better than nothing performing the fast-forward! - s = CalcWordWrapPositionA(scale, s, line_end ? line_end : text_end, wrap_width); + s = CalcWordWrapPosition(size, s, line_end ? line_end : text_end, wrap_width); s = CalcWordWrapNextLineStartA(s, text_end); } else @@ -5184,6 +6689,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im ImDrawVert* vtx_write = draw_list->_VtxWritePtr; ImDrawIdx* idx_write = draw_list->_IdxWritePtr; unsigned int vtx_index = draw_list->_VtxCurrentIdx; + const int cmd_count = draw_list->CmdBuffer.Size; const ImU32 col_untinted = col | ~IM_COL32_A_MASK; const char* word_wrap_eol = NULL; @@ -5194,7 +6700,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im { // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. if (!word_wrap_eol) - word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - origin_x)); + word_wrap_eol = CalcWordWrapPosition(size, s, text_end, wrap_width - (x - origin_x)); if (s >= word_wrap_eol) { @@ -5229,9 +6735,9 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im continue; } - const ImFontGlyph* glyph = FindGlyph((ImWchar)c); - if (glyph == NULL) - continue; + const ImFontGlyph* glyph = baked->FindGlyph((ImWchar)c); + //if (glyph == NULL) + // continue; float char_width = glyph->AdvanceX * scale; if (glyph->Visible) @@ -5299,6 +6805,20 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im x += char_width; } + // Edge case: calling RenderText() with unloaded glyphs triggering texture change. It doesn't happen via ImGui:: calls because CalcTextSize() is always used. + if (cmd_count != draw_list->CmdBuffer.Size) //-V547 + { + IM_ASSERT(draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ElemCount == 0); + draw_list->CmdBuffer.pop_back(); + draw_list->PrimUnreserve(idx_count_max, vtx_count_max); + draw_list->AddDrawCmd(); + //IMGUI_DEBUG_LOG("RenderText: cancel and retry to missing glyphs.\n"); // [DEBUG] + //draw_list->AddRectFilled(pos, pos + ImVec2(10, 10), IM_COL32(255, 0, 0, 255)); // [DEBUG] + goto begin; + //RenderText(draw_list, size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip); // FIXME-OPT: Would a 'goto begin' be better for code-gen? + //return; + } + // Give back unused vertices (clipped ones, blanks) ~ this is essentially a PrimUnreserve() action. draw_list->VtxBuffer.Size = (int)(vtx_write - draw_list->VtxBuffer.Data); // Same as calling shrink() draw_list->IdxBuffer.Size = (int)(idx_write - draw_list->IdxBuffer.Data); diff --git a/lib/third_party/imgui/imgui/source/imgui_tables.cpp b/lib/third_party/imgui/imgui/source/imgui_tables.cpp index c98aea2d1..119fe7bcc 100644 --- a/lib/third_party/imgui/imgui/source/imgui_tables.cpp +++ b/lib/third_party/imgui/imgui/source/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91b +// dear imgui, v1.92.1 // (tables and columns code) /* @@ -451,6 +451,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // But at this point we do NOT have a correct value for .Max.y (unless a height has been explicitly passed in). It will only be updated in EndTable(). table->WorkRect = table->OuterRect = table->InnerRect = outer_rect; table->HasScrollbarYPrev = table->HasScrollbarYCurr = false; + table->InnerWindow->DC.TreeDepth++; // This is designed to always linking ImGuiTreeNodeFlags_DrawLines linking accross a table } // Push a standardized ID for both child-using and not-child-using tables @@ -1250,7 +1251,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // [Part 11] Default context menu // - To append to this menu: you can call TableBeginContextMenuPopup()/.../EndPopup(). - // - To modify or replace this: set table->IsContextPopupNoDefaultContents = true, then call TableBeginContextMenuPopup()/.../EndPopup(). + // - To modify or replace this: set table->DisableDefaultContextMenu = true, then call TableBeginContextMenuPopup()/.../EndPopup(). // - You may call TableDrawDefaultContextMenu() with selected flags to display specific sections of the default menu, // e.g. TableDrawDefaultContextMenu(table, table->Flags & ~ImGuiTableFlags_Hideable) will display everything EXCEPT columns visibility options. if (table->DisableDefaultContextMenu == false && TableBeginContextMenuPopup(table)) @@ -1510,6 +1511,7 @@ void ImGui::EndTable() } else { + table->InnerWindow->DC.TreeDepth--; ItemSize(table->OuterRect.GetSize()); ItemAdd(table->OuterRect, 0); } @@ -1951,7 +1953,10 @@ void ImGui::TableEndRow(ImGuiTable* table) IM_ASSERT(table->IsInsideRow); if (table->CurrentColumn != -1) + { TableEndCell(table); + table->CurrentColumn = -1; + } // Logging if (g.LogEnabled) @@ -2191,6 +2196,7 @@ void ImGui::TableBeginCell(ImGuiTable* table, int column_n) g.LastItemData.StatusFlags = 0; } + // Also see TablePushColumnChannel() if (table->Flags & ImGuiTableFlags_NoClip) { // FIXME: if we end up drawing all borders/bg in EndTable, could remove this and just assert that channel hasn't changed. @@ -2464,10 +2470,38 @@ void ImGui::TablePopBackgroundChannel() ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiTable* table = g.CurrentTable; - ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; // Optimization: avoid PopClipRect() + SetCurrentChannel() SetWindowClipRectBeforeSetChannel(window, table->HostBackupInnerClipRect); + table->DrawSplitter->SetCurrentChannel(window->DrawList, table->Columns[table->CurrentColumn].DrawChannelCurrent); +} + +// Also see TableBeginCell() +void ImGui::TablePushColumnChannel(int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + + // Optimization: avoid SetCurrentChannel() + PushClipRect() + if (table->Flags & ImGuiTableFlags_NoClip) + return; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiTableColumn* column = &table->Columns[column_n]; + SetWindowClipRectBeforeSetChannel(window, column->ClipRect); + table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent); +} + +void ImGui::TablePopColumnChannel() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + + // Optimization: avoid PopClipRect() + SetCurrentChannel() + if ((table->Flags & ImGuiTableFlags_NoClip) || (table->CurrentColumn == -1)) // Calling TreePop() after TableNextRow() is supported. + return; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; + SetWindowClipRectBeforeSetChannel(window, column->ClipRect); table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent); } @@ -3244,7 +3278,7 @@ void ImGui::TableHeader(const char* label) // Render clipped label. Clipping here ensure that in the majority of situations, all our header cells will // be merged into a single draw call. //window->DrawList->AddCircleFilled(ImVec2(ellipsis_max, label_pos.y), 40, IM_COL32_WHITE); - RenderTextEllipsis(window->DrawList, label_pos, ImVec2(ellipsis_max, label_pos.y + label_height + g.Style.FramePadding.y), ellipsis_max, ellipsis_max, label, label_end, &label_size); + RenderTextEllipsis(window->DrawList, label_pos, ImVec2(ellipsis_max, bb.Max.y), ellipsis_max, label, label_end, &label_size); const bool text_clipped = label_size.x > (ellipsis_max - label_pos.x); if (text_clipped && hovered && g.ActiveId == 0) @@ -3341,7 +3375,7 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label ButtonBehavior(row_r, row_id, NULL, NULL); KeepAliveID(row_id); - const float ascent_scaled = g.Font->Ascent * g.FontScale; // FIXME: Standardize those scaling factors better + const float ascent_scaled = g.FontBaked->Ascent * g.FontBakedScale; // FIXME: Standardize those scaling factors better const float line_off_for_ascent_x = (ImMax((g.FontSize - ascent_scaled) * 0.5f, 0.0f) / -sin_a) * (flip_label ? -1.0f : 1.0f); const ImVec2 padding = g.Style.CellPadding; // We will always use swapped component const ImVec2 align = g.Style.TableAngledHeadersTextAlign; @@ -3396,7 +3430,7 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label ImRect clip_r(window->ClipRect.Min, window->ClipRect.Min + ImVec2(clip_width, clip_height)); int vtx_idx_begin = draw_list->_VtxCurrentIdx; PushStyleColor(ImGuiCol_Text, request->TextColor); - RenderTextEllipsis(draw_list, clip_r.Min, clip_r.Max, clip_r.Max.x, clip_r.Max.x, label_name, label_name_eol, &label_size); + RenderTextEllipsis(draw_list, clip_r.Min, clip_r.Max, clip_r.Max.x, label_name, label_name_eol, &label_size); PopStyleColor(); int vtx_idx_end = draw_list->_VtxCurrentIdx; diff --git a/lib/third_party/imgui/imgui/source/imgui_widgets.cpp b/lib/third_party/imgui/imgui/source/imgui_widgets.cpp index f4264b8a1..99c8f2006 100644 --- a/lib/third_party/imgui/imgui/source/imgui_widgets.cpp +++ b/lib/third_party/imgui/imgui/source/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.91b +// dear imgui, v1.92.1 // (widgets code) /* @@ -339,6 +339,46 @@ void ImGui::TextWrappedV(const char* fmt, va_list args) PopTextWrapPos(); } +void ImGui::TextAligned(float align_x, float size_x, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextAlignedV(align_x, size_x, fmt, args); + va_end(args); +} + +// align_x: 0.0f = left, 0.5f = center, 1.0f = right. +// size_x : 0.0f = shortcut for GetContentRegionAvail().x +// FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024) +void ImGui::TextAlignedV(float align_x, float size_x, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + const char* text, *text_end; + ImFormatStringToTempBufferV(&text, &text_end, fmt, args); + const ImVec2 text_size = CalcTextSize(text, text_end); + size_x = CalcItemSize(ImVec2(size_x, 0.0f), 0.0f, text_size.y).x; + + ImVec2 pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); + ImVec2 pos_max(pos.x + size_x, window->ClipRect.Max.y); + ImVec2 size(ImMin(size_x, text_size.x), text_size.y); + window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, pos.x + text_size.x); + window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, pos.x + text_size.x); + if (align_x > 0.0f && text_size.x < size_x) + pos.x += ImTrunc((size_x - text_size.x) * align_x); + RenderTextEllipsis(window->DrawList, pos, pos_max, pos_max.x, text, text_end, &text_size); + + const ImVec2 backup_max_pos = window->DC.CursorMaxPos; + ItemSize(size); + ItemAdd(ImRect(pos, pos + size), 0); + window->DC.CursorMaxPos.x = backup_max_pos.x; // Cancel out extending content size because right-aligned text would otherwise mess it up. + + if (size_x < text_size.x && IsItemHovered(ImGuiHoveredFlags_NoNavOverride | ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_ForTooltip)) + SetTooltip("%.*s", (int)(text_end - text), text); +} + void ImGui::LabelText(const char* label, const char* fmt, ...) { va_list args; @@ -494,7 +534,7 @@ void ImGui::BulletTextV(const char* fmt, va_list args) // And better standardize how widgets use 'GetColor32((held && hovered) ? ... : hovered ? ...)' vs 'GetColor32(held ? ... : hovered ? ...);' // For mouse feedback we typically prefer the 'held && hovered' test, but for nav feedback not always. Outputting hovered=true on Activation may be misleading. // - Since v1.91.2 (Sept 2024) we included io.ConfigDebugHighlightIdConflicts feature. -// One idiom which was previously valid which will now emit a warning is when using multiple overlayed ButtonBehavior() +// One idiom which was previously valid which will now emit a warning is when using multiple overlaid ButtonBehavior() // with same ID and different MouseButton (see #8030). You can fix it by: // (1) switching to use a single ButtonBehavior() with multiple _MouseButton flags. // or (2) surrounding those calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag() @@ -508,6 +548,8 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.ItemFlags : g.CurrentItemFlags); if (flags & ImGuiButtonFlags_AllowOverlap) item_flags |= ImGuiItemFlags_AllowOverlap; + if (item_flags & ImGuiItemFlags_NoFocus) + flags |= ImGuiButtonFlags_NoFocus | ImGuiButtonFlags_NoNavFocus; // Default only reacts to left mouse button if ((flags & ImGuiButtonFlags_MouseButtonMask_) == 0) @@ -531,7 +573,8 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool bool pressed = false; bool hovered = ItemHoverable(bb, id, item_flags); - // Special mode for Drag and Drop where holding button pressed for a long time while dragging another item triggers the button + // Special mode for Drag and Drop used by openables (tree nodes, tabs etc.) + // where holding the button pressed for a long time while drag a payload item triggers the button. if (g.DragDropActive && (flags & ImGuiButtonFlags_PressedOnDragDropHold) && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers)) if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) { @@ -583,7 +626,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool SetFocusID(id, window); FocusWindow(window); } - else + else if (!(flags & ImGuiButtonFlags_NoFocus)) { FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild); // Still need to focus and bring to front, but try to avoid losing NavId when navigating a child } @@ -601,7 +644,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool SetFocusID(id, window); FocusWindow(window); } - else + else if (!(flags & ImGuiButtonFlags_NoFocus)) { FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild); // Still need to focus and bring to front, but try to avoid losing NavId when navigating a child } @@ -867,11 +910,12 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos) if (hovered) window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col); RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact); - ImU32 cross_col = GetColorU32(ImGuiCol_Text); - ImVec2 cross_center = bb.GetCenter() - ImVec2(0.5f, 0.5f); - float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f; - window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, +cross_extent), cross_center + ImVec2(-cross_extent, -cross_extent), cross_col, 1.0f); - window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, -cross_extent), cross_center + ImVec2(-cross_extent, +cross_extent), cross_col, 1.0f); + const ImU32 cross_col = GetColorU32(ImGuiCol_Text); + const ImVec2 cross_center = bb.GetCenter() - ImVec2(0.5f, 0.5f); + const float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f; + const float cross_thickness = 1.0f; // FIXME-DPI + window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, +cross_extent), cross_center + ImVec2(-cross_extent, -cross_extent), cross_col, cross_thickness); + window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, -cross_extent), cross_center + ImVec2(-cross_extent, +cross_extent), cross_col, cross_thickness); return pressed; } @@ -1068,9 +1112,9 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6 return held; } -// - Read about ImTextureID here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples +// - Read about ImTextureID/ImTextureRef here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples // - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above. -void ImGui::ImageWithBg(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col) +void ImGui::ImageWithBg(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); @@ -1088,28 +1132,28 @@ void ImGui::ImageWithBg(ImTextureID user_texture_id, const ImVec2& image_size, c window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border), 0.0f, ImDrawFlags_None, g.Style.ImageBorderSize); if (bg_col.w > 0.0f) window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col)); - window->DrawList->AddImage(user_texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); + window->DrawList->AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); } -void ImGui::Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1) +void ImGui::Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1) { - ImageWithBg(user_texture_id, image_size, uv0, uv1); + ImageWithBg(tex_ref, image_size, uv0, uv1); } // 1.91.9 (February 2025) removed 'tint_col' and 'border_col' parameters, made border size not depend on color value. (#8131, #8238) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -void ImGui::Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) +void ImGui::Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) { ImGuiContext& g = *GImGui; PushStyleVar(ImGuiStyleVar_ImageBorderSize, (border_col.w > 0.0f) ? ImMax(1.0f, g.Style.ImageBorderSize) : 0.0f); // Preserve legacy behavior where border is always visible when border_col's Alpha is >0.0f PushStyleColor(ImGuiCol_Border, border_col); - ImageWithBg(user_texture_id, image_size, uv0, uv1, ImVec4(0, 0, 0, 0), tint_col); + ImageWithBg(tex_ref, image_size, uv0, uv1, ImVec4(0, 0, 0, 0), tint_col); PopStyleColor(); PopStyleVar(); } #endif -bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags) +bool ImGui::ImageButtonEx(ImGuiID id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); @@ -1131,21 +1175,21 @@ bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID user_texture_id, const ImVec2& RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, g.Style.FrameRounding)); if (bg_col.w > 0.0f) window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col)); - window->DrawList->AddImage(user_texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); + window->DrawList->AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); return pressed; } // - ImageButton() adds style.FramePadding*2.0f to provided size. This is in order to facilitate fitting an image in a button. // - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified. (#8165) // FIXME: Maybe that's not the best design? -bool ImGui::ImageButton(const char* str_id, ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col) +bool ImGui::ImageButton(const char* str_id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->SkipItems) return false; - return ImageButtonEx(window->GetID(str_id), user_texture_id, image_size, uv0, uv1, bg_col, tint_col); + return ImageButtonEx(window->GetID(str_id), tex_ref, image_size, uv0, uv1, bg_col, tint_col); } #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS @@ -1483,8 +1527,8 @@ bool ImGui::TextLink(const char* label) ColorConvertHSVtoRGB(h, s, v, line_colf.x, line_colf.y, line_colf.z); } - float line_y = bb.Max.y + ImFloor(g.Font->Descent * g.FontScale * 0.20f); - window->DrawList->AddLine(ImVec2(bb.Min.x, line_y), ImVec2(bb.Max.x, line_y), GetColorU32(line_colf)); // FIXME-TEXT: Underline mode. + float line_y = bb.Max.y + ImFloor(g.FontBaked->Descent * g.FontBakedScale * 0.20f); + window->DrawList->AddLine(ImVec2(bb.Min.x, line_y), ImVec2(bb.Max.x, line_y), GetColorU32(line_colf)); // FIXME-TEXT: Underline mode // FIXME-DPI PushStyleColor(ImGuiCol_Text, GetColorU32(text_colf)); RenderText(bb.Min, label, label_end); @@ -1494,14 +1538,14 @@ bool ImGui::TextLink(const char* label) return pressed; } -void ImGui::TextLinkOpenURL(const char* label, const char* url) +bool ImGui::TextLinkOpenURL(const char* label, const char* url) { ImGuiContext& g = *GImGui; if (url == NULL) url = label; - if (TextLink(label)) - if (g.PlatformIO.Platform_OpenInShellFn != NULL) - g.PlatformIO.Platform_OpenInShellFn(&g, url); + bool pressed = TextLink(label); + if (pressed && g.PlatformIO.Platform_OpenInShellFn != NULL) + g.PlatformIO.Platform_OpenInShellFn(&g, url); SetItemTooltip(LocalizeGetMsg(ImGuiLocKey_OpenLink_s), url); // It is more reassuring for user to _always_ display URL when we same as label if (BeginPopupContextItem()) { @@ -1509,6 +1553,7 @@ void ImGui::TextLinkOpenURL(const char* label, const char* url) SetClipboardText(url); EndPopup(); } + return pressed; } //------------------------------------------------------------------------- @@ -1695,7 +1740,7 @@ void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end window->DrawList->AddLine(ImVec2(sep2_x1, seps_y), ImVec2(sep2_x2, seps_y), separator_col, separator_thickness); if (g.LogEnabled) LogSetNextTextDecoration("---", NULL); - RenderTextEllipsis(window->DrawList, label_pos, ImVec2(bb.Max.x, bb.Max.y + style.ItemSpacing.y), bb.Max.x, bb.Max.x, label, label_end, &label_size); + RenderTextEllipsis(window->DrawList, label_pos, ImVec2(bb.Max.x, bb.Max.y + style.ItemSpacing.y), bb.Max.x, label, label_end, &label_size); } else { @@ -3896,7 +3941,7 @@ bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, si return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data); } -// This is only used in the path where the multiline widget is inactivate. +// This is only used in the path where the multiline widget is inactive. static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end) { int line_count = 0; @@ -3920,9 +3965,10 @@ static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end, const char** remaining, ImVec2* out_offset, bool stop_on_new_line) { ImGuiContext& g = *ctx; - ImFont* font = g.Font; + //ImFont* font = g.Font; + ImFontBaked* baked = g.FontBaked; const float line_height = g.FontSize; - const float scale = line_height / font->FontSize; + const float scale = line_height / baked->Size; ImVec2 text_size = ImVec2(0, 0); float line_width = 0.0f; @@ -3948,8 +3994,7 @@ static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, c if (c == '\r') continue; - const float char_width = ((int)c < font->IndexAdvanceX.Size ? font->IndexAdvanceX.Data[c] : font->FallbackAdvanceX) * scale; - line_width += char_width; + line_width += baked->GetCharAdvance((ImWchar)c) * scale; } if (text_size.x < line_width) @@ -3976,7 +4021,7 @@ namespace ImStb { static int STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj) { return obj->TextLen; } static char STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx) { IM_ASSERT(idx <= obj->TextLen); return obj->TextSrc[idx]; } -static float STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx) { unsigned int c; ImTextCharFromUtf8(&c, obj->TextSrc + line_start_idx + char_idx, obj->TextSrc + obj->TextLen); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.Font->GetCharAdvance((ImWchar)c) * g.FontScale; } +static float STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx) { unsigned int c; ImTextCharFromUtf8(&c, obj->TextSrc + line_start_idx + char_idx, obj->TextSrc + obj->TextLen); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.FontBaked->GetCharAdvance((ImWchar)c) * g.FontBakedScale; } static char STB_TEXTEDIT_NEWLINE = '\n'; static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx) { @@ -4244,23 +4289,24 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons if (new_text == new_text_end) return; + ImGuiContext& g = *Ctx; + ImGuiInputTextState* obj = &g.InputTextState; + IM_ASSERT(obj->ID != 0 && g.ActiveId == obj->ID); + // Grow internal buffer if needed const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0; const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)ImStrlen(new_text); - if (new_text_len + BufTextLen >= BufSize) + if (new_text_len + BufTextLen + 1 > obj->TextA.Size && (Flags & ImGuiInputTextFlags_ReadOnly) == 0) { if (!is_resizable) return; - ImGuiContext& g = *Ctx; - ImGuiInputTextState* edit_state = &g.InputTextState; - IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID); - IM_ASSERT(Buf == edit_state->TextA.Data); + IM_ASSERT(Buf == obj->TextA.Data); int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1; - edit_state->TextA.resize(new_buf_size + 1); - edit_state->TextSrc = edit_state->TextA.Data; - Buf = edit_state->TextA.Data; - BufSize = edit_state->BufCapacity = new_buf_size; + obj->TextA.resize(new_buf_size + 1); + obj->TextSrc = obj->TextA.Data; + Buf = obj->TextA.Data; + BufSize = obj->BufCapacity = new_buf_size; } if (BufTextLen != pos) @@ -4278,18 +4324,29 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons void ImGui::PushPasswordFont() { ImGuiContext& g = *GImGui; - ImFont* in_font = g.Font; - ImFont* out_font = &g.InputTextPasswordFont; - ImFontGlyph* glyph = in_font->FindGlyph('*'); - out_font->FontSize = in_font->FontSize; - out_font->Scale = in_font->Scale; - out_font->Ascent = in_font->Ascent; - out_font->Descent = in_font->Descent; - out_font->ContainerAtlas = in_font->ContainerAtlas; - out_font->FallbackGlyph = glyph; - out_font->FallbackAdvanceX = glyph->AdvanceX; - IM_ASSERT(out_font->Glyphs.Size == 0 && out_font->IndexAdvanceX.Size == 0 && out_font->IndexLookup.Size == 0); - PushFont(out_font); + ImFontBaked* backup = &g.InputTextPasswordFontBackupBaked; + IM_ASSERT(backup->IndexAdvanceX.Size == 0 && backup->IndexLookup.Size == 0); + ImFontGlyph* glyph = g.FontBaked->FindGlyph('*'); + g.InputTextPasswordFontBackupFlags = g.Font->Flags; + backup->FallbackGlyphIndex = g.FontBaked->FallbackGlyphIndex; + backup->FallbackAdvanceX = g.FontBaked->FallbackAdvanceX; + backup->IndexLookup.swap(g.FontBaked->IndexLookup); + backup->IndexAdvanceX.swap(g.FontBaked->IndexAdvanceX); + g.Font->Flags |= ImFontFlags_NoLoadGlyphs; + g.FontBaked->FallbackGlyphIndex = g.FontBaked->Glyphs.index_from_ptr(glyph); + g.FontBaked->FallbackAdvanceX = glyph->AdvanceX; +} + +void ImGui::PopPasswordFont() +{ + ImGuiContext& g = *GImGui; + ImFontBaked* backup = &g.InputTextPasswordFontBackupBaked; + g.Font->Flags = g.InputTextPasswordFontBackupFlags; + g.FontBaked->FallbackGlyphIndex = backup->FallbackGlyphIndex; + g.FontBaked->FallbackAdvanceX = backup->FallbackAdvanceX; + g.FontBaked->IndexLookup.swap(backup->IndexLookup); + g.FontBaked->IndexAdvanceX.swap(backup->IndexAdvanceX); + IM_ASSERT(backup->IndexAdvanceX.Size == 0 && backup->IndexLookup.Size == 0); } // Return false to discard a character. @@ -4653,7 +4710,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (g.ActiveId == id) { // Declare some inputs, the other are registered and polled via Shortcut() routing system. - // FIXME: The reason we don't use Shortcut() is we would need a routing flag to specify multiple mods, or to all mods combinaison into individual shortcuts. + // FIXME: The reason we don't use Shortcut() is we would need a routing flag to specify multiple mods, or to all mods combination into individual shortcuts. const ImGuiKey always_owned_keys[] = { ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_Enter, ImGuiKey_KeypadEnter, ImGuiKey_Delete, ImGuiKey_Backspace, ImGuiKey_Home, ImGuiKey_End }; for (ImGuiKey key : always_owned_keys) SetKeyOwner(key, id); @@ -5166,8 +5223,6 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Otherwise request text input ahead for next frame. if (g.ActiveId == id && clear_active_id) ClearActiveID(); - else if (g.ActiveId == id) - g.WantTextInputNextFrame = 1; // Render frame if (!is_multiline) @@ -5193,7 +5248,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (new_is_displaying_hint != is_displaying_hint) { if (is_password && !is_displaying_hint) - PopFont(); + PopPasswordFont(); is_displaying_hint = new_is_displaying_hint; if (is_password && !is_displaying_hint) PushPasswordFont(); @@ -5318,7 +5373,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ else { ImVec2 rect_size = InputTextCalcTextSize(&g, p, text_selected_end, &p, NULL, true); - if (rect_size.x <= 0.0f) rect_size.x = IM_TRUNC(g.Font->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines + if (rect_size.x <= 0.0f) rect_size.x = IM_TRUNC(g.FontBaked->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos + ImVec2(rect_size.x, bg_offy_dn)); rect.ClipWith(clip_rect); if (rect.Overlaps(clip_rect)) @@ -5345,15 +5400,19 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ ImVec2 cursor_screen_pos = ImTrunc(draw_pos + cursor_offset - draw_scroll); ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f); if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) - draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text)); + draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_InputTextCursor), 1.0f); // FIXME-DPI: Cursor thickness (#7031) // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) - if (!is_readonly) + // This is required for some backends (SDL3) to start emitting character/text inputs. + // As per #6341, make sure we don't set that on the deactivating frame. + if (!is_readonly && g.ActiveId == id) { - g.PlatformImeData.WantVisible = true; - g.PlatformImeData.InputPos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize); - g.PlatformImeData.InputLineHeight = g.FontSize; - g.PlatformImeViewport = window->Viewport->ID; + ImGuiPlatformImeData* ime_data = &g.PlatformImeData; // (this is a public struct, passed to io.Platform_SetImeDataFn() handler) + ime_data->WantVisible = true; + ime_data->WantTextInput = true; + ime_data->InputPos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize); + ime_data->InputLineHeight = g.FontSize; + ime_data->ViewportId = window->Viewport->ID; } } } @@ -5380,7 +5439,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } if (is_password && !is_displaying_hint) - PopFont(); + PopPasswordFont(); if (is_multiline) { @@ -5432,7 +5491,7 @@ void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state) Text("ID: 0x%08X, ActiveID: 0x%08X", state->ID, g.ActiveId); DebugLocateItemOnHover(state->ID); Text("CurLenA: %d, Cursor: %d, Selection: %d..%d", state->TextLen, stb_state->cursor, stb_state->select_start, stb_state->select_end); - Text("BufCapacityA: %d", state->BufCapacity); + Text("BufCapacity: %d", state->BufCapacity); Text("(Internal Buffer: TextA Size: %d, Capacity: %d)", state->TextA.Size, state->TextA.Capacity); Text("has_preferred_x: %d (%.2f)", stb_state->has_preferred_x, stb_state->preferred_x); Text("undo_point: %d, redo_point: %d, undo_char_point: %d, redo_char_point: %d", undo_state->undo_point, undo_state->redo_point, undo_state->undo_char_point, undo_state->redo_char_point); @@ -6214,7 +6273,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl if (g.Style.FrameBorderSize > 0.0f) RenderFrameBorder(bb.Min, bb.Max, rounding); else - window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color buttons are often in need of some sort of border + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color buttons are often in need of some sort of border // FIXME-DPI } // Drag and Drop Source @@ -6396,6 +6455,7 @@ void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags fl // - TreeNodeV() // - TreeNodeEx() // - TreeNodeExV() +// - TreeNodeStoreStackData() [Internal] // - TreeNodeBehavior() [Internal] // - TreePush() // - TreePop() @@ -6554,18 +6614,26 @@ bool ImGui::TreeNodeUpdateNextOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags) // Store ImGuiTreeNodeStackData for just submitted node. // Currently only supports 32 level deep and we are fine with (1 << Depth) overflowing into a zero, easy to increase. -static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags) +static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags, float x1) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; g.TreeNodeStack.resize(g.TreeNodeStack.Size + 1); - ImGuiTreeNodeStackData* tree_node_data = &g.TreeNodeStack.back(); + ImGuiTreeNodeStackData* tree_node_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; tree_node_data->ID = g.LastItemData.ID; tree_node_data->TreeFlags = flags; tree_node_data->ItemFlags = g.LastItemData.ItemFlags; tree_node_data->NavRect = g.LastItemData.NavRect; + + // Initially I tried to latch value for GetColorU32(ImGuiCol_TreeLines) but it's not a good trade-off for very large trees. + const bool draw_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) != 0; + tree_node_data->DrawLinesX1 = draw_lines ? (x1 + g.FontSize * 0.5f + g.Style.FramePadding.x) : +FLT_MAX; + tree_node_data->DrawLinesTableColumn = (draw_lines && g.CurrentTable) ? (ImGuiTableColumnIdx)g.CurrentTable->CurrentColumn : -1; + tree_node_data->DrawLinesToNodesY2 = -FLT_MAX; window->DC.TreeHasStackDataDepthMask |= (1 << window->DC.TreeDepth); + if (flags & ImGuiTreeNodeFlags_DrawLinesToNodes) + window->DC.TreeRecordsClippedNodesY2Mask |= (1 << window->DC.TreeDepth); } // When using public API, currently 'id == storage_id' is always true, but we separate the values to facilitate advanced user code doing storage queries outside of UI loop. @@ -6635,14 +6703,18 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDisplayRect; g.LastItemData.DisplayRect = frame_bb; - // If a NavLeft request is happening and ImGuiTreeNodeFlags_NavLeftJumpsBackHere enabled: + // If a NavLeft request is happening and ImGuiTreeNodeFlags_NavLeftJumpsToParent enabled: // Store data for the current depth to allow returning to this node from any child item. // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop(). - // It will become tempting to enable ImGuiTreeNodeFlags_NavLeftJumpsBackHere by default or move it to ImGuiStyle. + // It will become tempting to enable ImGuiTreeNodeFlags_NavLeftJumpsToParent by default or move it to ImGuiStyle. bool store_tree_node_stack_data = false; + if ((flags & ImGuiTreeNodeFlags_DrawLinesMask_) == 0) + flags |= g.Style.TreeLinesFlags; + const bool draw_tree_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) && (frame_bb.Min.y < window->ClipRect.Max.y) && (g.Style.TreeLinesSize > 0.0f); if (!(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) { - if ((flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && is_open && !g.NavIdIsAlive) + store_tree_node_stack_data = draw_tree_lines; + if ((flags & ImGuiTreeNodeFlags_NavLeftJumpsToParent) && !g.NavIdIsAlive) if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) store_tree_node_stack_data = true; } @@ -6650,8 +6722,15 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l const bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0; if (!is_visible) { - if (store_tree_node_stack_data && is_open) - TreeNodeStoreStackData(flags); // Call before TreePushOverrideID() + if ((flags & ImGuiTreeNodeFlags_DrawLinesToNodes) && (window->DC.TreeRecordsClippedNodesY2Mask & (1 << (window->DC.TreeDepth - 1)))) + { + ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; + parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, window->DC.CursorPos.y); // Don't need to aim to mid Y position as we are clipped anyway. + if (frame_bb.Min.y >= window->ClipRect.Max.y) + window->DC.TreeRecordsClippedNodesY2Mask &= ~(1 << (window->DC.TreeDepth - 1)); // Done + } + if (is_open && store_tree_node_stack_data) + TreeNodeStoreStackData(flags, text_pos.x - text_offset_x); // Call before TreePushOverrideID() if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) TreePushOverrideID(id); IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0)); @@ -6697,6 +6776,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; else button_flags |= ImGuiButtonFlags_PressedOnClickRelease; + if (flags & ImGuiTreeNodeFlags_NoNavFocus) + button_flags |= ImGuiButtonFlags_NoNavFocus; bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0; const bool was_selected = selected; @@ -6783,6 +6864,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding); RenderNavCursor(frame_bb, id, nav_render_cursor_flags); + if (span_all_columns && !span_all_columns_label) + TablePopBackgroundChannel(); if (flags & ImGuiTreeNodeFlags_Bullet) RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.60f, text_pos.y + g.FontSize * 0.5f), text_col); else if (!is_leaf) @@ -6803,6 +6886,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false); } RenderNavCursor(frame_bb, id, nav_render_cursor_flags); + if (span_all_columns && !span_all_columns_label) + TablePopBackgroundChannel(); if (flags & ImGuiTreeNodeFlags_Bullet) RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.5f, text_pos.y + g.FontSize * 0.5f), text_col); else if (!is_leaf) @@ -6811,8 +6896,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l LogSetNextTextDecoration(">", NULL); } - if (span_all_columns && !span_all_columns_label) - TablePopBackgroundChannel(); + if (draw_tree_lines) + TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.5f)); // Label if (display_frame) @@ -6824,8 +6909,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l TablePopBackgroundChannel(); } - if (store_tree_node_stack_data && is_open) - TreeNodeStoreStackData(flags); // Call before TreePushOverrideID() + if (is_open && store_tree_node_stack_data) + TreeNodeStoreStackData(flags, text_pos.x - text_offset_x); // Call before TreePushOverrideID() if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) TreePushOverrideID(id); // Could use TreePush(label) but this avoid computing twice @@ -6833,6 +6918,64 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l return is_open; } +// Draw horizontal line from our parent node +// This is only called for visible child nodes so we are not too fussy anymore about performances +void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->DC.TreeDepth == 0 || (window->DC.TreeHasStackDataDepthMask & (1 << (window->DC.TreeDepth - 1))) == 0) + return; + + ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; + float x1 = ImTrunc(parent_data->DrawLinesX1); + float x2 = ImTrunc(target_pos.x - g.Style.ItemInnerSpacing.x); + float y = ImTrunc(target_pos.y); + float rounding = (g.Style.TreeLinesRounding > 0.0f) ? ImMin(x2 - x1, g.Style.TreeLinesRounding) : 0.0f; + parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, y - rounding); + if (x1 >= x2) + return; + if (rounding > 0.0f) + { + x1 += 0.5f + rounding; + window->DrawList->PathArcToFast(ImVec2(x1, y - rounding), rounding, 6, 3); + if (x1 < x2) + window->DrawList->PathLineTo(ImVec2(x2, y)); + window->DrawList->PathStroke(GetColorU32(ImGuiCol_TreeLines), ImDrawFlags_None, g.Style.TreeLinesSize); + } + else + { + window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); + } +} + +// Draw vertical line of the hierarchy +void ImGui::TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + float y1 = ImMax(data->NavRect.Max.y, window->ClipRect.Min.y); + float y2 = data->DrawLinesToNodesY2; + if (data->TreeFlags & ImGuiTreeNodeFlags_DrawLinesFull) + { + float y2_full = window->DC.CursorPos.y; + if (g.CurrentTable) + y2_full = ImMax(g.CurrentTable->RowPosY2, y2_full); + y2_full = ImTrunc(y2_full - g.Style.ItemSpacing.y - g.FontSize * 0.5f); + if (y2 + (g.Style.ItemSpacing.y + g.Style.TreeLinesRounding) < y2_full) // FIXME: threshold to use ToNodes Y2 instead of Full Y2 when close by ItemSpacing.y + y2 = y2_full; + } + y2 = ImMin(y2, window->ClipRect.Max.y); + if (y2 <= y1) + return; + float x = ImTrunc(data->DrawLinesX1); + if (data->DrawLinesTableColumn != -1) + TablePushColumnChannel(data->DrawLinesTableColumn); + window->DrawList->AddLine(ImVec2(x, y1), ImVec2(x, y2), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); + if (data->DrawLinesTableColumn != -1) + TablePopColumnChannel(); +} + void ImGui::TreePush(const char* str_id) { ImGuiWindow* window = GetCurrentWindow(); @@ -6867,18 +7010,23 @@ void ImGui::TreePop() window->DC.TreeDepth--; ImU32 tree_depth_mask = (1 << window->DC.TreeDepth); - if (window->DC.TreeHasStackDataDepthMask & tree_depth_mask) // Only set during request + if (window->DC.TreeHasStackDataDepthMask & tree_depth_mask) { - ImGuiTreeNodeStackData* data = &g.TreeNodeStack.back(); + const ImGuiTreeNodeStackData* data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; IM_ASSERT(data->ID == window->IDStack.back()); - if (data->TreeFlags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) - { - // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsBackHere is enabled) + + // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsToParent is enabled) + if (data->TreeFlags & ImGuiTreeNodeFlags_NavLeftJumpsToParent) if (g.NavIdIsAlive && g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) NavMoveRequestResolveWithPastTreeNode(&g.NavMoveResultLocal, data); - } + + // Draw hierarchy lines + if (data->DrawLinesX1 != +FLT_MAX && window->DC.CursorPos.y >= window->ClipRect.Min.y) + TreeNodeDrawLineToTreePop(data); + g.TreeNodeStack.pop_back(); window->DC.TreeHasStackDataDepthMask &= ~tree_depth_mask; + window->DC.TreeRecordsClippedNodesY2Mask &= ~tree_depth_mask; } IM_ASSERT(window->IDStack.Size > 1); // There should always be 1 element in the IDStack (pushed during window creation). If this triggers you called TreePop/PopID too much. @@ -7493,7 +7641,7 @@ void ImGui::EndBoxSelect(const ImRect& scope_rect, ImGuiMultiSelectFlags ms_flag ImRect box_select_r = bs->BoxSelectRectCurr; box_select_r.ClipWith(scope_rect); window->DrawList->AddRectFilled(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_SeparatorHovered, 0.30f)); // FIXME-MULTISELECT: Styling - window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavCursor)); // FIXME-MULTISELECT: Styling + window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavCursor)); // FIXME-MULTISELECT FIXME-DPI: Styling // Scroll const bool enable_scroll = (ms_flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms_flags & ImGuiMultiSelectFlags_BoxSelectNoScroll) == 0; @@ -7697,7 +7845,7 @@ ImGuiMultiSelectIO* ImGui::EndMultiSelect() if (ms->IsFocused) { // We currently don't allow user code to modify RangeSrcItem by writing to BeginIO's version, but that would be an easy change here. - if (ms->IO.RangeSrcReset || (ms->RangeSrcPassedBy == false && ms->IO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) // Can't read storage->RangeSrcItem here -> we want the state at begining of the scope (see tests for easy failure) + if (ms->IO.RangeSrcReset || (ms->RangeSrcPassedBy == false && ms->IO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) // Can't read storage->RangeSrcItem here -> we want the state at beginning of the scope (see tests for easy failure) { IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset RangeSrcItem.\n"); // Will set be to NavId. storage->RangeSrcItem = ImGuiSelectionUserData_Invalid; @@ -8783,7 +8931,6 @@ bool ImGui::BeginViewportSideBar(const char* name, ImGuiViewport* viewport_p, Im } window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking; - // Create window SetNextWindowViewport(viewport->ID); // Enforce viewport so we don't create our own viewport when ImGuiConfigFlags_ViewportsNoMerge is set. PushStyleColor(ImGuiCol_WindowShadow, ImVec4(0, 0, 0, 0)); @@ -10505,13 +10652,12 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, #endif // Render text label (with clipping + alpha gradient) + unsaved marker - ImRect text_pixel_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y); - ImRect text_ellipsis_clip_bb = text_pixel_clip_bb; + ImRect text_ellipsis_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y); // Return clipped state ignoring the close button if (out_text_clipped) { - *out_text_clipped = (text_ellipsis_clip_bb.Min.x + label_size.x) > text_pixel_clip_bb.Max.x; + *out_text_clipped = (text_ellipsis_clip_bb.Min.x + label_size.x) > text_ellipsis_clip_bb.Max.x; //draw_list->AddCircle(text_ellipsis_clip_bb.Min, 3.0f, *out_text_clipped ? IM_COL32(255, 0, 0, 255) : IM_COL32(0, 255, 0, 255)); } @@ -10557,15 +10703,22 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, // This is all rather complicated // (the main idea is that because the close button only appears on hover, we don't want it to alter the ellipsis position) // FIXME: if FramePadding is noticeably large, ellipsis_max_x will be wrong here (e.g. #3497), maybe for consistency that parameter of RenderTextEllipsis() shouldn't exist.. - float ellipsis_max_x = close_button_visible ? text_pixel_clip_bb.Max.x : bb.Max.x - 1.0f; + float ellipsis_max_x = text_ellipsis_clip_bb.Max.x; if (close_button_visible || unsaved_marker_visible) { - text_pixel_clip_bb.Max.x -= close_button_visible ? (button_sz) : (button_sz * 0.80f); - text_ellipsis_clip_bb.Max.x -= unsaved_marker_visible ? (button_sz * 0.80f) : 0.0f; - ellipsis_max_x = text_pixel_clip_bb.Max.x; + const bool visible_without_hover = unsaved_marker_visible || (is_contents_visible ? g.Style.TabCloseButtonMinWidthSelected : g.Style.TabCloseButtonMinWidthUnselected) < 0.0f; + if (visible_without_hover) + { + text_ellipsis_clip_bb.Max.x -= button_sz * 0.90f; + ellipsis_max_x -= button_sz * 0.90f; + } + else + { + text_ellipsis_clip_bb.Max.x -= button_sz * 1.00f; + } } LogSetNextTextDecoration("/", "\\"); - RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, text_pixel_clip_bb.Max.x, ellipsis_max_x, label, NULL, &label_size); + RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, ellipsis_max_x, label, NULL, &label_size); #if 0 if (!is_contents_visible) diff --git a/lib/third_party/imgui/imgui/source/misc/freetype/imgui_freetype.cpp b/lib/third_party/imgui/imgui/source/misc/freetype/imgui_freetype.cpp index 6acf8c88b..30b397bae 100644 --- a/lib/third_party/imgui/imgui/source/misc/freetype/imgui_freetype.cpp +++ b/lib/third_party/imgui/imgui/source/misc/freetype/imgui_freetype.cpp @@ -2,10 +2,12 @@ // (code) // Get the latest version at https://github.com/ocornut/imgui/tree/master/misc/freetype -// Original code by @vuhdo (Aleksei Skriabin). Improvements by @mikesart. Maintained since 2019 by @ocornut. +// Original code by @vuhdo (Aleksei Skriabin) in 2017, with improvements by @mikesart. +// Maintained since 2019 by @ocornut. // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2025/06/11: refactored for the new ImFontLoader architecture, and ImGuiBackendFlags_RendererHasTextures support. // 2024/10/17: added plutosvg support for SVG Fonts (seems faster/better than lunasvg). Enable by using '#define IMGUI_ENABLE_FREETYPE_PLUTOSVG'. (#7927) // 2023/11/13: added support for ImFontConfig::RasterizationDensity field for scaling render density without scaling metrics. // 2023/08/01: added support for SVG fonts, enable by using '#define IMGUI_ENABLE_FREETYPE_LUNASVG'. (#6591) @@ -44,6 +46,7 @@ #include FT_FREETYPE_H // #include FT_MODULE_H // #include FT_GLYPH_H // +#include FT_SIZES_H // #include FT_SYNTHESIS_H // // Handle LunaSVG and PlutoSVG @@ -107,666 +110,228 @@ static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_ #define FT_CEIL(X) (((X + 63) & -64) / 64) // From SDL_ttf: Handy routines for converting from fixed point #define FT_SCALEFACTOR 64.0f -namespace +// Glyph metrics: +// -------------- +// +// xmin xmax +// | | +// |<-------- width -------->| +// | | +// | +-------------------------+----------------- ymax +// | | ggggggggg ggggg | ^ ^ +// | | g:::::::::ggg::::g | | | +// | | g:::::::::::::::::g | | | +// | | g::::::ggggg::::::gg | | | +// | | g:::::g g:::::g | | | +// offsetX -|-------->| g:::::g g:::::g | offsetY | +// | | g:::::g g:::::g | | | +// | | g::::::g g:::::g | | | +// | | g:::::::ggggg:::::g | | | +// | | g::::::::::::::::g | | height +// | | gg::::::::::::::g | | | +// baseline ---*---------|---- gggggggg::::::g-----*-------- | +// / | | g:::::g | | +// origin | | gggggg g:::::g | | +// | | g:::::gg gg:::::g | | +// | | g::::::ggg:::::::g | | +// | | gg:::::::::::::g | | +// | | ggg::::::ggg | | +// | | gggggg | v +// | +-------------------------+----------------- ymin +// | | +// |------------- advanceX ----------->| + +// Stored in ImFontAtlas::FontLoaderData. ALLOCATED BY US. +struct ImGui_ImplFreeType_Data { - // Glyph metrics: - // -------------- - // - // xmin xmax - // | | - // |<-------- width -------->| - // | | - // | +-------------------------+----------------- ymax - // | | ggggggggg ggggg | ^ ^ - // | | g:::::::::ggg::::g | | | - // | | g:::::::::::::::::g | | | - // | | g::::::ggggg::::::gg | | | - // | | g:::::g g:::::g | | | - // offsetX -|-------->| g:::::g g:::::g | offsetY | - // | | g:::::g g:::::g | | | - // | | g::::::g g:::::g | | | - // | | g:::::::ggggg:::::g | | | - // | | g::::::::::::::::g | | height - // | | gg::::::::::::::g | | | - // baseline ---*---------|---- gggggggg::::::g-----*-------- | - // / | | g:::::g | | - // origin | | gggggg g:::::g | | - // | | g:::::gg gg:::::g | | - // | | g::::::ggg:::::::g | | - // | | gg:::::::::::::g | | - // | | ggg::::::ggg | | - // | | gggggg | v - // | +-------------------------+----------------- ymin - // | | - // |------------- advanceX ----------->| - - // A structure that describe a glyph. - struct GlyphInfo - { - int Width; // Glyph's width in pixels. - int Height; // Glyph's height in pixels. - FT_Int OffsetX; // The distance from the origin ("pen position") to the left of the glyph. - FT_Int OffsetY; // The distance from the origin to the top of the glyph. This is usually a value < 0. - float AdvanceX; // The distance from the origin to the origin of the next glyph. This is usually a value > 0. - bool IsColored; // The glyph is colored - }; - - // Font parameters and metrics. - struct FontInfo - { - uint32_t PixelHeight; // Size this font was generated with. - float Ascender; // The pixel extents above the baseline in pixels (typically positive). - float Descender; // The extents below the baseline in pixels (typically negative). - float LineSpacing; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate. - float LineGap; // The spacing in pixels between one row's descent and the next row's ascent. - float MaxAdvanceWidth; // This field gives the maximum horizontal cursor advance for all glyphs in the font. - }; - - // FreeType glyph rasterizer. - // NB: No ctor/dtor, explicitly call Init()/Shutdown() - struct FreeTypeFont - { - bool InitFont(FT_Library ft_library, const ImFontConfig& src, unsigned int extra_user_flags); // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime. - void CloseFont(); - void SetPixelHeight(int pixel_height); // Change font pixel size. All following calls to RasterizeGlyph() will use this size - const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint); - const FT_Bitmap* RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info); - void BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table = nullptr); - FreeTypeFont() { memset((void*)this, 0, sizeof(*this)); } - ~FreeTypeFont() { CloseFont(); } - - // [Internals] - FontInfo Info; // Font descriptor of the current font. - FT_Face Face; - unsigned int UserFlags; // = ImFontConfig::RasterizerFlags - FT_Int32 LoadFlags; - FT_Render_Mode RenderMode; - float RasterizationDensity; - float InvRasterizationDensity; - }; - - bool FreeTypeFont::InitFont(FT_Library ft_library, const ImFontConfig& src, unsigned int extra_font_builder_flags) - { - FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src.FontData, (uint32_t)src.FontDataSize, (uint32_t)src.FontNo, &Face); - if (error != 0) - return false; - error = FT_Select_Charmap(Face, FT_ENCODING_UNICODE); - if (error != 0) - return false; - - // Convert to FreeType flags (NB: Bold and Oblique are processed separately) - UserFlags = src.FontBuilderFlags | extra_font_builder_flags; - - LoadFlags = 0; - if ((UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) == 0) - LoadFlags |= FT_LOAD_NO_BITMAP; - - if (UserFlags & ImGuiFreeTypeBuilderFlags_NoHinting) - LoadFlags |= FT_LOAD_NO_HINTING; - if (UserFlags & ImGuiFreeTypeBuilderFlags_NoAutoHint) - LoadFlags |= FT_LOAD_NO_AUTOHINT; - if (UserFlags & ImGuiFreeTypeBuilderFlags_ForceAutoHint) - LoadFlags |= FT_LOAD_FORCE_AUTOHINT; - if (UserFlags & ImGuiFreeTypeBuilderFlags_LightHinting) - LoadFlags |= FT_LOAD_TARGET_LIGHT; - else if (UserFlags & ImGuiFreeTypeBuilderFlags_MonoHinting) - LoadFlags |= FT_LOAD_TARGET_MONO; - else - LoadFlags |= FT_LOAD_TARGET_NORMAL; - - if (UserFlags & ImGuiFreeTypeBuilderFlags_Monochrome) - RenderMode = FT_RENDER_MODE_MONO; - else - RenderMode = FT_RENDER_MODE_NORMAL; - - if (UserFlags & ImGuiFreeTypeBuilderFlags_LoadColor) - LoadFlags |= FT_LOAD_COLOR; - - RasterizationDensity = src.RasterizerDensity; - InvRasterizationDensity = 1.0f / RasterizationDensity; - - memset(&Info, 0, sizeof(Info)); - SetPixelHeight((uint32_t)src.SizePixels); - - return true; - } - - void FreeTypeFont::CloseFont() - { - if (Face) - { - FT_Done_Face(Face); - Face = nullptr; - } - } - - void FreeTypeFont::SetPixelHeight(int pixel_height) - { - // Vuhdo: I'm not sure how to deal with font sizes properly. As far as I understand, currently ImGui assumes that the 'pixel_height' - // is a maximum height of an any given glyph, i.e. it's the sum of font's ascender and descender. Seems strange to me. - // NB: FT_Set_Pixel_Sizes() doesn't seem to get us the same result. - FT_Size_RequestRec req; - req.type = (UserFlags & ImGuiFreeTypeBuilderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM; - req.width = 0; - req.height = (uint32_t)(pixel_height * 64 * RasterizationDensity); - req.horiResolution = 0; - req.vertResolution = 0; - FT_Request_Size(Face, &req); - - // Update font info - FT_Size_Metrics metrics = Face->size->metrics; - Info.PixelHeight = (uint32_t)(pixel_height * InvRasterizationDensity); - Info.Ascender = (float)FT_CEIL(metrics.ascender) * InvRasterizationDensity; - Info.Descender = (float)FT_CEIL(metrics.descender) * InvRasterizationDensity; - Info.LineSpacing = (float)FT_CEIL(metrics.height) * InvRasterizationDensity; - Info.LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender) * InvRasterizationDensity; - Info.MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * InvRasterizationDensity; - } - - const FT_Glyph_Metrics* FreeTypeFont::LoadGlyph(uint32_t codepoint) - { - uint32_t glyph_index = FT_Get_Char_Index(Face, codepoint); - if (glyph_index == 0) - return nullptr; - - // If this crash for you: FreeType 2.11.0 has a crash bug on some bitmap/colored fonts. - // - https://gitlab.freedesktop.org/freetype/freetype/-/issues/1076 - // - https://github.com/ocornut/imgui/issues/4567 - // - https://github.com/ocornut/imgui/issues/4566 - // You can use FreeType 2.10, or the patched version of 2.11.0 in VcPkg, or probably any upcoming FreeType version. - FT_Error error = FT_Load_Glyph(Face, glyph_index, LoadFlags); - if (error) - return nullptr; - - // Need an outline for this to work - FT_GlyphSlot slot = Face->glyph; -#if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) || defined(IMGUI_ENABLE_FREETYPE_PLUTOSVG) - IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP || slot->format == FT_GLYPH_FORMAT_SVG); -#else -#if ((FREETYPE_MAJOR >= 2) && (FREETYPE_MINOR >= 12)) - IM_ASSERT(slot->format != FT_GLYPH_FORMAT_SVG && "The font contains SVG glyphs, you'll need to enable IMGUI_ENABLE_FREETYPE_PLUTOSVG or IMGUI_ENABLE_FREETYPE_LUNASVG in imconfig.h and install required libraries in order to use this font"); -#endif - IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP); -#endif // IMGUI_ENABLE_FREETYPE_LUNASVG - - // Apply convenience transform (this is not picking from real "Bold"/"Italic" fonts! Merely applying FreeType helper transform. Oblique == Slanting) - if (UserFlags & ImGuiFreeTypeBuilderFlags_Bold) - FT_GlyphSlot_Embolden(slot); - if (UserFlags & ImGuiFreeTypeBuilderFlags_Oblique) - { - FT_GlyphSlot_Oblique(slot); - //FT_BBox bbox; - //FT_Outline_Get_BBox(&slot->outline, &bbox); - //slot->metrics.width = bbox.xMax - bbox.xMin; - //slot->metrics.height = bbox.yMax - bbox.yMin; - } - - return &slot->metrics; - } - - const FT_Bitmap* FreeTypeFont::RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info) - { - FT_GlyphSlot slot = Face->glyph; - FT_Error error = FT_Render_Glyph(slot, RenderMode); - if (error != 0) - return nullptr; - - FT_Bitmap* ft_bitmap = &Face->glyph->bitmap; - out_glyph_info->Width = (int)ft_bitmap->width; - out_glyph_info->Height = (int)ft_bitmap->rows; - out_glyph_info->OffsetX = Face->glyph->bitmap_left; - out_glyph_info->OffsetY = -Face->glyph->bitmap_top; - out_glyph_info->AdvanceX = (float)slot->advance.x / FT_SCALEFACTOR; - out_glyph_info->IsColored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA); - - return ft_bitmap; - } - - void FreeTypeFont::BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch, unsigned char* multiply_table) - { - IM_ASSERT(ft_bitmap != nullptr); - const uint32_t w = ft_bitmap->width; - const uint32_t h = ft_bitmap->rows; - const uint8_t* src = ft_bitmap->buffer; - const uint32_t src_pitch = ft_bitmap->pitch; - - switch (ft_bitmap->pixel_mode) - { - case FT_PIXEL_MODE_GRAY: // Grayscale image, 1 byte per pixel. - { - if (multiply_table == nullptr) - { - for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) - for (uint32_t x = 0; x < w; x++) - dst[x] = IM_COL32(255, 255, 255, src[x]); - } - else - { - for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) - for (uint32_t x = 0; x < w; x++) - dst[x] = IM_COL32(255, 255, 255, multiply_table[src[x]]); - } - break; - } - case FT_PIXEL_MODE_MONO: // Monochrome image, 1 bit per pixel. The bits in each byte are ordered from MSB to LSB. - { - uint8_t color0 = multiply_table ? multiply_table[0] : 0; - uint8_t color1 = multiply_table ? multiply_table[255] : 255; - for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) - { - uint8_t bits = 0; - const uint8_t* bits_ptr = src; - for (uint32_t x = 0; x < w; x++, bits <<= 1) - { - if ((x & 7) == 0) - bits = *bits_ptr++; - dst[x] = IM_COL32(255, 255, 255, (bits & 0x80) ? color1 : color0); - } - } - break; - } - case FT_PIXEL_MODE_BGRA: - { - // FIXME: Converting pre-multiplied alpha to straight. Doesn't smell good. - #define DE_MULTIPLY(color, alpha) ImMin((ImU32)(255.0f * (float)color / (float)(alpha + FLT_MIN) + 0.5f), 255u) - if (multiply_table == nullptr) - { - for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) - for (uint32_t x = 0; x < w; x++) - { - uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3]; - dst[x] = IM_COL32(DE_MULTIPLY(r, a), DE_MULTIPLY(g, a), DE_MULTIPLY(b, a), a); - } - } - else - { - for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) - { - for (uint32_t x = 0; x < w; x++) - { - uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3]; - dst[x] = IM_COL32(multiply_table[DE_MULTIPLY(r, a)], multiply_table[DE_MULTIPLY(g, a)], multiply_table[DE_MULTIPLY(b, a)], multiply_table[a]); - } - } - } - #undef DE_MULTIPLY - break; - } - default: - IM_ASSERT(0 && "FreeTypeFont::BlitGlyph(): Unknown bitmap pixel mode!"); - } - } -} // namespace - -#ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds) -#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION -#define STBRP_ASSERT(x) do { IM_ASSERT(x); } while (0) -#define STBRP_STATIC -#define STB_RECT_PACK_IMPLEMENTATION -#endif -#ifdef IMGUI_STB_RECT_PACK_FILENAME -#include IMGUI_STB_RECT_PACK_FILENAME -#else -#include "imstb_rectpack.h" -#endif -#endif - -struct ImFontBuildSrcGlyphFT -{ - GlyphInfo Info; - uint32_t Codepoint; - unsigned int* BitmapData; // Point within one of the dst_tmp_bitmap_buffers[] array - - ImFontBuildSrcGlyphFT() { memset((void*)this, 0, sizeof(*this)); } + FT_Library Library; + FT_MemoryRec_ MemoryManager; + ImGui_ImplFreeType_Data() { memset((void*)this, 0, sizeof(*this)); } }; -struct ImFontBuildSrcDataFT +// Stored in ImFontConfig::FontLoaderData. ALLOCATED BY US. +struct ImGui_ImplFreeType_FontSrcData { - FreeTypeFont Font; - stbrp_rect* Rects; // Rectangle to pack. We first fill in their size and the packer will give us their position. - const ImWchar* SrcRanges; // Ranges as requested by user (user is allowed to request too much, e.g. 0x0020..0xFFFF) - int DstIndex; // Index into atlas->Fonts[] and dst_tmp_array[] - int GlyphsHighest; // Highest requested codepoint - int GlyphsCount; // Glyph count (excluding missing glyphs and glyphs already set by an earlier source font) - ImBitVector GlyphsSet; // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB) - ImVector GlyphsList; + // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime. + bool InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeLoaderFlags extra_user_flags); + void CloseFont(); + ImGui_ImplFreeType_FontSrcData() { memset((void*)this, 0, sizeof(*this)); } + ~ImGui_ImplFreeType_FontSrcData() { CloseFont(); } + + // Members + FT_Face FtFace; + ImGuiFreeTypeLoaderFlags UserFlags; // = ImFontConfig::FontLoaderFlags + FT_Int32 LoadFlags; + ImFontBaked* BakedLastActivated; }; -// Temporary data for one destination ImFont* (multiple source fonts can be merged into one destination ImFont) -struct ImFontBuildDstDataFT +// Stored in ImFontBaked::FontLoaderDatas: pointer to SourcesCount instances of this. ALLOCATED BY CORE. +struct ImGui_ImplFreeType_FontSrcBakedData { - int SrcCount; // Number of source fonts targeting this destination font. - int GlyphsHighest; - int GlyphsCount; - ImBitVector GlyphsSet; // This is used to resolve collision when multiple sources are merged into a same destination font. + FT_Size FtSize; // This represent a FT_Face with a given size. + ImGui_ImplFreeType_FontSrcBakedData() { memset((void*)this, 0, sizeof(*this)); } }; -bool ImFontAtlasBuildWithFreeTypeEx(FT_Library ft_library, ImFontAtlas* atlas, unsigned int extra_flags) +bool ImGui_ImplFreeType_FontSrcData::InitFont(FT_Library ft_library, ImFontConfig* src, ImGuiFreeTypeLoaderFlags extra_font_loader_flags) { - IM_ASSERT(atlas->Sources.Size > 0); + FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)src->FontData, (FT_Long)src->FontDataSize, (FT_Long)src->FontNo, &FtFace); + if (error != 0) + return false; + error = FT_Select_Charmap(FtFace, FT_ENCODING_UNICODE); + if (error != 0) + return false; - ImFontAtlasBuildInit(atlas); + // Convert to FreeType flags (NB: Bold and Oblique are processed separately) + UserFlags = (ImGuiFreeTypeLoaderFlags)(src->FontLoaderFlags | extra_font_loader_flags); - // Clear atlas - atlas->TexID = 0; - atlas->TexWidth = atlas->TexHeight = 0; - atlas->TexUvScale = ImVec2(0.0f, 0.0f); - atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f); - atlas->ClearTexData(); + LoadFlags = 0; + if ((UserFlags & ImGuiFreeTypeLoaderFlags_Bitmap) == 0) + LoadFlags |= FT_LOAD_NO_BITMAP; - // Temporary storage for building - bool src_load_color = false; - ImVector src_tmp_array; - ImVector dst_tmp_array; - src_tmp_array.resize(atlas->Sources.Size); - dst_tmp_array.resize(atlas->Fonts.Size); - memset((void*)src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes()); - memset((void*)dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes()); - - // 1. Initialize font loading structure, check font data validity - for (int src_i = 0; src_i < atlas->Sources.Size; src_i++) - { - ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i]; - ImFontConfig& src = atlas->Sources[src_i]; - FreeTypeFont& font_face = src_tmp.Font; - IM_ASSERT(src.DstFont && (!src.DstFont->IsLoaded() || src.DstFont->ContainerAtlas == atlas)); - - // Find index from src.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices) - src_tmp.DstIndex = -1; - for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++) - if (src.DstFont == atlas->Fonts[output_i]) - src_tmp.DstIndex = output_i; - IM_ASSERT(src_tmp.DstIndex != -1); // src.DstFont not pointing within atlas->Fonts[] array? - if (src_tmp.DstIndex == -1) - return false; - - // Load font - if (!font_face.InitFont(ft_library, src, extra_flags)) - return false; - - // Measure highest codepoints - src_load_color |= (src.FontBuilderFlags & ImGuiFreeTypeBuilderFlags_LoadColor) != 0; - ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex]; - src_tmp.SrcRanges = src.GlyphRanges ? src.GlyphRanges : atlas->GetGlyphRangesDefault(); - for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) - { - // Check for valid range. This may also help detect *some* dangling pointers, because a common - // user error is to setup ImFontConfig::GlyphRanges with a pointer to data that isn't persistent, - // or to forget to zero-terminate the glyph range array. - IM_ASSERT(src_range[0] <= src_range[1] && "Invalid range: is your glyph range array persistent? it is zero-terminated?"); - src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]); - } - dst_tmp.SrcCount++; - dst_tmp.GlyphsHighest = ImMax(dst_tmp.GlyphsHighest, src_tmp.GlyphsHighest); - } - - // 2. For every requested codepoint, check for their presence in the font data, and handle redundancy or overlaps between source fonts to avoid unused glyphs. - int total_glyphs_count = 0; - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i]; - ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex]; - src_tmp.GlyphsSet.Create(src_tmp.GlyphsHighest + 1); - if (dst_tmp.GlyphsSet.Storage.empty()) - dst_tmp.GlyphsSet.Create(dst_tmp.GlyphsHighest + 1); - - for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) - for (int codepoint = src_range[0]; codepoint <= (int)src_range[1]; codepoint++) - { - if (dst_tmp.GlyphsSet.TestBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option (e.g. MergeOverwrite) - continue; - uint32_t glyph_index = FT_Get_Char_Index(src_tmp.Font.Face, codepoint); // It is actually in the font? (FIXME-OPT: We are not storing the glyph_index..) - if (glyph_index == 0) - continue; - - // Add to avail set/counters - src_tmp.GlyphsCount++; - dst_tmp.GlyphsCount++; - src_tmp.GlyphsSet.SetBit(codepoint); - dst_tmp.GlyphsSet.SetBit(codepoint); - total_glyphs_count++; - } - } - - // 3. Unpack our bit map into a flat list (we now have all the Unicode points that we know are requested _and_ available _and_ not overlapping another) - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i]; - src_tmp.GlyphsList.reserve(src_tmp.GlyphsCount); - - IM_ASSERT(sizeof(src_tmp.GlyphsSet.Storage.Data[0]) == sizeof(ImU32)); - const ImU32* it_begin = src_tmp.GlyphsSet.Storage.begin(); - const ImU32* it_end = src_tmp.GlyphsSet.Storage.end(); - for (const ImU32* it = it_begin; it < it_end; it++) - if (ImU32 entries_32 = *it) - for (ImU32 bit_n = 0; bit_n < 32; bit_n++) - if (entries_32 & ((ImU32)1 << bit_n)) - { - ImFontBuildSrcGlyphFT src_glyph; - src_glyph.Codepoint = (ImWchar)(((it - it_begin) << 5) + bit_n); - //src_glyph.GlyphIndex = 0; // FIXME-OPT: We had this info in the previous step and lost it.. - src_tmp.GlyphsList.push_back(src_glyph); - } - src_tmp.GlyphsSet.Clear(); - IM_ASSERT(src_tmp.GlyphsList.Size == src_tmp.GlyphsCount); - } - for (int dst_i = 0; dst_i < dst_tmp_array.Size; dst_i++) - dst_tmp_array[dst_i].GlyphsSet.Clear(); - dst_tmp_array.clear(); - - // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0) - // (We technically don't need to zero-clear buf_rects, but let's do it for the sake of sanity) - ImVector buf_rects; - buf_rects.resize(total_glyphs_count); - memset(buf_rects.Data, 0, (size_t)buf_rects.size_in_bytes()); - - // Allocate temporary rasterization data buffers. - // We could not find a way to retrieve accurate glyph size without rendering them. - // (e.g. slot->metrics->width not always matching bitmap->width, especially considering the Oblique transform) - // We allocate in chunks of 256 KB to not waste too much extra memory ahead. Hopefully users of FreeType won't mind the temporary allocations. - const int BITMAP_BUFFERS_CHUNK_SIZE = 256 * 1024; - int buf_bitmap_current_used_bytes = 0; - ImVector buf_bitmap_buffers; - buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE)); - - // 4. Gather glyphs sizes so we can pack them in our virtual canvas. - // 8. Render/rasterize font characters into the texture - int total_surface = 0; - int buf_rects_out_n = 0; - const int pack_padding = atlas->TexGlyphPadding; - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i]; - ImFontConfig& src = atlas->Sources[src_i]; - if (src_tmp.GlyphsCount == 0) - continue; - - src_tmp.Rects = &buf_rects[buf_rects_out_n]; - buf_rects_out_n += src_tmp.GlyphsCount; - - // Compute multiply table if requested - const bool multiply_enabled = (src.RasterizerMultiply != 1.0f); - unsigned char multiply_table[256]; - if (multiply_enabled) - ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, src.RasterizerMultiply); - - // Gather the sizes of all rectangles we will need to pack - for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++) - { - ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i]; - - const FT_Glyph_Metrics* metrics = src_tmp.Font.LoadGlyph(src_glyph.Codepoint); - if (metrics == nullptr) - continue; - - // Render glyph into a bitmap (currently held by FreeType) - const FT_Bitmap* ft_bitmap = src_tmp.Font.RenderGlyphAndGetInfo(&src_glyph.Info); - if (ft_bitmap == nullptr) - continue; - - // Allocate new temporary chunk if needed - const int bitmap_size_in_bytes = src_glyph.Info.Width * src_glyph.Info.Height * 4; - if (buf_bitmap_current_used_bytes + bitmap_size_in_bytes > BITMAP_BUFFERS_CHUNK_SIZE) - { - buf_bitmap_current_used_bytes = 0; - buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE)); - } - IM_ASSERT(buf_bitmap_current_used_bytes + bitmap_size_in_bytes <= BITMAP_BUFFERS_CHUNK_SIZE); // We could probably allocate custom-sized buffer instead. - - // Blit rasterized pixels to our temporary buffer and keep a pointer to it. - src_glyph.BitmapData = (unsigned int*)(buf_bitmap_buffers.back() + buf_bitmap_current_used_bytes); - buf_bitmap_current_used_bytes += bitmap_size_in_bytes; - src_tmp.Font.BlitGlyph(ft_bitmap, src_glyph.BitmapData, src_glyph.Info.Width, multiply_enabled ? multiply_table : nullptr); - - src_tmp.Rects[glyph_i].w = (stbrp_coord)(src_glyph.Info.Width + pack_padding); - src_tmp.Rects[glyph_i].h = (stbrp_coord)(src_glyph.Info.Height + pack_padding); - total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h; - } - } - for (int i = 0; i < atlas->CustomRects.Size; i++) - total_surface += (atlas->CustomRects[i].Width + pack_padding) * (atlas->CustomRects[i].Height + pack_padding); - - // We need a width for the skyline algorithm, any width! - // The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height. - // User can override TexDesiredWidth and TexGlyphPadding if they wish, otherwise we use a simple heuristic to select the width based on expected surface. - const int surface_sqrt = (int)ImSqrt((float)total_surface) + 1; - atlas->TexHeight = 0; - if (atlas->TexDesiredWidth > 0) - atlas->TexWidth = atlas->TexDesiredWidth; + if (UserFlags & ImGuiFreeTypeLoaderFlags_NoHinting) + LoadFlags |= FT_LOAD_NO_HINTING; else - atlas->TexWidth = (surface_sqrt >= 4096 * 0.7f) ? 4096 : (surface_sqrt >= 2048 * 0.7f) ? 2048 : (surface_sqrt >= 1024 * 0.7f) ? 1024 : 512; + src->PixelSnapH = true; // FIXME: A bit weird to do this this way. - // 5. Start packing - // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). - const int TEX_HEIGHT_MAX = 1024 * 32; - const int num_nodes_for_packing_algorithm = atlas->TexWidth - atlas->TexGlyphPadding; - ImVector pack_nodes; - pack_nodes.resize(num_nodes_for_packing_algorithm); - stbrp_context pack_context; - stbrp_init_target(&pack_context, atlas->TexWidth - atlas->TexGlyphPadding, TEX_HEIGHT_MAX - atlas->TexGlyphPadding, pack_nodes.Data, pack_nodes.Size); - ImFontAtlasBuildPackCustomRects(atlas, &pack_context); - - // 6. Pack each source font. No rendering yet, we are working with rectangles in an infinitely tall texture at this point. - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i]; - // IMHEX PATCH BEGIN - // if (src_tmp.GlyphsCount == 0) - // continue; - // IMHEX PATCH END - - stbrp_pack_rects(&pack_context, src_tmp.Rects, src_tmp.GlyphsCount); - - // Extend texture height and mark missing glyphs as non-packed so we won't render them. - // FIXME: We are not handling packing failure here (would happen if we got off TEX_HEIGHT_MAX or if a single if larger than TexWidth?) - for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++) - if (src_tmp.Rects[glyph_i].was_packed) - atlas->TexHeight = ImMax(atlas->TexHeight, src_tmp.Rects[glyph_i].y + src_tmp.Rects[glyph_i].h); - } - - // 7. Allocate texture - atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight); - atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight); - if (src_load_color) - { - size_t tex_size = (size_t)atlas->TexWidth * atlas->TexHeight * 4; - atlas->TexPixelsRGBA32 = (unsigned int*)IM_ALLOC(tex_size); - memset(atlas->TexPixelsRGBA32, 0, tex_size); - } + if (UserFlags & ImGuiFreeTypeLoaderFlags_NoAutoHint) + LoadFlags |= FT_LOAD_NO_AUTOHINT; + if (UserFlags & ImGuiFreeTypeLoaderFlags_ForceAutoHint) + LoadFlags |= FT_LOAD_FORCE_AUTOHINT; + if (UserFlags & ImGuiFreeTypeLoaderFlags_LightHinting) + LoadFlags |= FT_LOAD_TARGET_LIGHT; + else if (UserFlags & ImGuiFreeTypeLoaderFlags_MonoHinting) + LoadFlags |= FT_LOAD_TARGET_MONO; else - { - size_t tex_size = (size_t)atlas->TexWidth * atlas->TexHeight * 1; - atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(tex_size); - memset(atlas->TexPixelsAlpha8, 0, tex_size); - } + LoadFlags |= FT_LOAD_TARGET_NORMAL; - // 8. Copy rasterized font characters back into the main texture - // 9. Setup ImFont and glyphs for runtime - bool tex_use_colors = false; - for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) - { - ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i]; - - // When merging fonts with MergeMode=true: - // - We can have multiple input fonts writing into a same destination font. - // - dst_font->Sources is != from src which is our source configuration. - ImFontConfig& src = atlas->Sources[src_i]; - ImFont* dst_font = src.DstFont; - - const float ascent = src_tmp.Font.Info.Ascender; - const float descent = src_tmp.Font.Info.Descender; - ImFontAtlasBuildSetupFont(atlas, dst_font, &src, ascent, descent); - - if (src_tmp.GlyphsCount == 0) - continue; - const float font_off_x = src.GlyphOffset.x; - const float font_off_y = src.GlyphOffset.y + IM_ROUND(dst_font->Ascent); - - const int padding = atlas->TexGlyphPadding; - for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++) - { - ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i]; - stbrp_rect& pack_rect = src_tmp.Rects[glyph_i]; - IM_ASSERT(pack_rect.was_packed); - if (pack_rect.w == 0 && pack_rect.h == 0) - continue; - - GlyphInfo& info = src_glyph.Info; - IM_ASSERT(info.Width + padding <= pack_rect.w); - IM_ASSERT(info.Height + padding <= pack_rect.h); - const int tx = pack_rect.x + padding; - const int ty = pack_rect.y + padding; - - // Register glyph - float x0 = info.OffsetX * src_tmp.Font.InvRasterizationDensity + font_off_x; - float y0 = info.OffsetY * src_tmp.Font.InvRasterizationDensity + font_off_y; - float x1 = x0 + info.Width * src_tmp.Font.InvRasterizationDensity; - float y1 = y0 + info.Height * src_tmp.Font.InvRasterizationDensity; - float u0 = (tx) / (float)atlas->TexWidth; - float v0 = (ty) / (float)atlas->TexHeight; - float u1 = (tx + info.Width) / (float)atlas->TexWidth; - float v1 = (ty + info.Height) / (float)atlas->TexHeight; - dst_font->AddGlyph(&src, (ImWchar)src_glyph.Codepoint, x0, y0, x1, y1, u0, v0, u1, v1, info.AdvanceX * src_tmp.Font.InvRasterizationDensity); - - ImFontGlyph* dst_glyph = &dst_font->Glyphs.back(); - IM_ASSERT(dst_glyph->Codepoint == src_glyph.Codepoint); - if (src_glyph.Info.IsColored) - dst_glyph->Colored = tex_use_colors = true; - - // Blit from temporary buffer to final texture - size_t blit_src_stride = (size_t)src_glyph.Info.Width; - size_t blit_dst_stride = (size_t)atlas->TexWidth; - unsigned int* blit_src = src_glyph.BitmapData; - if (atlas->TexPixelsAlpha8 != nullptr) - { - unsigned char* blit_dst = atlas->TexPixelsAlpha8 + (ty * blit_dst_stride) + tx; - for (int y = 0; y < info.Height; y++, blit_dst += blit_dst_stride, blit_src += blit_src_stride) - for (int x = 0; x < info.Width; x++) - blit_dst[x] = (unsigned char)((blit_src[x] >> IM_COL32_A_SHIFT) & 0xFF); - } - else - { - unsigned int* blit_dst = atlas->TexPixelsRGBA32 + (ty * blit_dst_stride) + tx; - for (int y = 0; y < info.Height; y++, blit_dst += blit_dst_stride, blit_src += blit_src_stride) - for (int x = 0; x < info.Width; x++) - blit_dst[x] = blit_src[x]; - } - } - - src_tmp.Rects = nullptr; - } - atlas->TexPixelsUseColors = tex_use_colors; - - // Cleanup - for (int buf_i = 0; buf_i < buf_bitmap_buffers.Size; buf_i++) - IM_FREE(buf_bitmap_buffers[buf_i]); - src_tmp_array.clear_destruct(); - - ImFontAtlasBuildFinish(atlas); + if (UserFlags & ImGuiFreeTypeLoaderFlags_LoadColor) + LoadFlags |= FT_LOAD_COLOR; + // IMHEX PATCH BEGIN + if (UserFlags & ImGuiFreeTypeLoaderFlags_SubPixel) + LoadFlags |= FT_LOAD_TARGET_LCD | FT_LOAD_RENDER; + // IMHEX PATCH END return true; } +void ImGui_ImplFreeType_FontSrcData::CloseFont() +{ + if (FtFace) + { + FT_Done_Face(FtFace); + FtFace = nullptr; + } +} + +static const FT_Glyph_Metrics* ImGui_ImplFreeType_LoadGlyph(ImGui_ImplFreeType_FontSrcData* src_data, uint32_t codepoint) +{ + uint32_t glyph_index = FT_Get_Char_Index(src_data->FtFace, codepoint); + if (glyph_index == 0) + return nullptr; + + // If this crash for you: FreeType 2.11.0 has a crash bug on some bitmap/colored fonts. + // - https://gitlab.freedesktop.org/freetype/freetype/-/issues/1076 + // - https://github.com/ocornut/imgui/issues/4567 + // - https://github.com/ocornut/imgui/issues/4566 + // You can use FreeType 2.10, or the patched version of 2.11.0 in VcPkg, or probably any upcoming FreeType version. + FT_Error error = FT_Load_Glyph(src_data->FtFace, glyph_index, src_data->LoadFlags); + if (error) + return nullptr; + + // Need an outline for this to work + FT_GlyphSlot slot = src_data->FtFace->glyph; +#if defined(IMGUI_ENABLE_FREETYPE_LUNASVG) || defined(IMGUI_ENABLE_FREETYPE_PLUTOSVG) + IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP || slot->format == FT_GLYPH_FORMAT_SVG); +#else +#if ((FREETYPE_MAJOR >= 2) && (FREETYPE_MINOR >= 12)) + IM_ASSERT(slot->format != FT_GLYPH_FORMAT_SVG && "The font contains SVG glyphs, you'll need to enable IMGUI_ENABLE_FREETYPE_PLUTOSVG or IMGUI_ENABLE_FREETYPE_LUNASVG in imconfig.h and install required libraries in order to use this font"); +#endif + IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE || slot->format == FT_GLYPH_FORMAT_BITMAP); +#endif // IMGUI_ENABLE_FREETYPE_LUNASVG + + // Apply convenience transform (this is not picking from real "Bold"/"Italic" fonts! Merely applying FreeType helper transform. Oblique == Slanting) + if (src_data->UserFlags & ImGuiFreeTypeLoaderFlags_Bold) + FT_GlyphSlot_Embolden(slot); + if (src_data->UserFlags & ImGuiFreeTypeLoaderFlags_Oblique) + { + FT_GlyphSlot_Oblique(slot); + //FT_BBox bbox; + //FT_Outline_Get_BBox(&slot->outline, &bbox); + //slot->metrics.width = bbox.xMax - bbox.xMin; + //slot->metrics.height = bbox.yMax - bbox.yMin; + } + + return &slot->metrics; +} + +static void ImGui_ImplFreeType_BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* dst, uint32_t dst_pitch) +{ + IM_ASSERT(ft_bitmap != nullptr); + const uint32_t w = ft_bitmap->width; + const uint32_t h = ft_bitmap->rows; + const uint8_t* src = ft_bitmap->buffer; + const uint32_t src_pitch = ft_bitmap->pitch; + + switch (ft_bitmap->pixel_mode) + { + case FT_PIXEL_MODE_GRAY: // Grayscale image, 1 byte per pixel. + { + for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) + for (uint32_t x = 0; x < w; x++) + dst[x] = IM_COL32(255, 255, 255, src[x]); + break; + } + case FT_PIXEL_MODE_MONO: // Monochrome image, 1 bit per pixel. The bits in each byte are ordered from MSB to LSB. + { + for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) + { + uint8_t bits = 0; + const uint8_t* bits_ptr = src; + for (uint32_t x = 0; x < w; x++, bits <<= 1) + { + if ((x & 7) == 0) + bits = *bits_ptr++; + dst[x] = IM_COL32(255, 255, 255, (bits & 0x80) ? 255 : 0); + } + } + break; + } + case FT_PIXEL_MODE_BGRA: + { + // FIXME: Converting pre-multiplied alpha to straight. Doesn't smell good. + #define DE_MULTIPLY(color, alpha) ImMin((ImU32)(255.0f * (float)color / (float)(alpha + FLT_MIN) + 0.5f), 255u) + for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) + for (uint32_t x = 0; x < w; x++) + { + uint8_t r = src[x * 4 + 2], g = src[x * 4 + 1], b = src[x * 4], a = src[x * 4 + 3]; + dst[x] = IM_COL32(DE_MULTIPLY(r, a), DE_MULTIPLY(g, a), DE_MULTIPLY(b, a), a); + } + #undef DE_MULTIPLY + break; + } + // IMHEX PATCH BEGIN + case FT_PIXEL_MODE_LCD: + { + memset(dst, 0x00, (size_t)w * h * sizeof(uint32_t)); + for (uint32_t y = 0; y < h; y++) { + for (uint32_t x = 0; x < w / 3; x++) { + dst[x] = IM_COL32(src[x * 3 + 0], src[x * 3 + 1], src[x * 3 + 2], (src[x * 3 + 0] + src[x * 3 + 1] + src[x * 3 + 2]) / 3); + + if (dst[x] == 0x00FFFFFF) + dst[x] = 0x00000000; + } + + src += src_pitch; + dst += dst_pitch; + } + break; + } + // IMHEX PATCH END + default: + IM_ASSERT(0 && "FreeTypeFont::BlitGlyph(): Unknown bitmap pixel mode!"); + } +} + // FreeType memory allocation callbacks static void* FreeType_Alloc(FT_Memory /*memory*/, long size) { @@ -801,47 +366,250 @@ static void* FreeType_Realloc(FT_Memory /*memory*/, long cur_size, long new_size return block; } -static bool ImFontAtlasBuildWithFreeType(ImFontAtlas* atlas) +bool ImGui_ImplFreeType_LoaderInit(ImFontAtlas* atlas) { + IM_ASSERT(atlas->FontLoaderData == nullptr); + ImGui_ImplFreeType_Data* bd = IM_NEW(ImGui_ImplFreeType_Data)(); + // FreeType memory management: https://www.freetype.org/freetype2/docs/design/design-4.html - FT_MemoryRec_ memory_rec = {}; - memory_rec.user = nullptr; - memory_rec.alloc = &FreeType_Alloc; - memory_rec.free = &FreeType_Free; - memory_rec.realloc = &FreeType_Realloc; + bd->MemoryManager.user = nullptr; + bd->MemoryManager.alloc = &FreeType_Alloc; + bd->MemoryManager.free = &FreeType_Free; + bd->MemoryManager.realloc = &FreeType_Realloc; // https://www.freetype.org/freetype2/docs/reference/ft2-module_management.html#FT_New_Library - FT_Library ft_library; - FT_Error error = FT_New_Library(&memory_rec, &ft_library); + FT_Error error = FT_New_Library(&bd->MemoryManager, &bd->Library); if (error != 0) + { + IM_DELETE(bd); return false; + } // If you don't call FT_Add_Default_Modules() the rest of code may work, but FreeType won't use our custom allocator. - FT_Add_Default_Modules(ft_library); + FT_Add_Default_Modules(bd->Library); #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG // Install svg hooks for FreeType // https://freetype.org/freetype2/docs/reference/ft2-properties.html#svg-hooks // https://freetype.org/freetype2/docs/reference/ft2-svg_fonts.html#svg_fonts SVG_RendererHooks hooks = { ImGuiLunasvgPortInit, ImGuiLunasvgPortFree, ImGuiLunasvgPortRender, ImGuiLunasvgPortPresetSlot }; - FT_Property_Set(ft_library, "ot-svg", "svg-hooks", &hooks); + FT_Property_Set(bd->Library, "ot-svg", "svg-hooks", &hooks); #endif // IMGUI_ENABLE_FREETYPE_LUNASVG #ifdef IMGUI_ENABLE_FREETYPE_PLUTOSVG // With plutosvg, use provided hooks - FT_Property_Set(ft_library, "ot-svg", "svg-hooks", plutosvg_ft_svg_hooks()); + FT_Property_Set(bd->Library, "ot-svg", "svg-hooks", plutosvg_ft_svg_hooks()); #endif // IMGUI_ENABLE_FREETYPE_PLUTOSVG - bool ret = ImFontAtlasBuildWithFreeTypeEx(ft_library, atlas, atlas->FontBuilderFlags); - FT_Done_Library(ft_library); + // Store our data + atlas->FontLoaderData = (void*)bd; - return ret; + return true; } -const ImFontBuilderIO* ImGuiFreeType::GetBuilderForFreeType() +void ImGui_ImplFreeType_LoaderShutdown(ImFontAtlas* atlas) { - static ImFontBuilderIO io; - io.FontBuilder_Build = ImFontAtlasBuildWithFreeType; - return &io; + ImGui_ImplFreeType_Data* bd = (ImGui_ImplFreeType_Data*)atlas->FontLoaderData; + IM_ASSERT(bd != nullptr); + FT_Done_Library(bd->Library); + IM_DELETE(bd); + atlas->FontLoaderData = nullptr; +} + +bool ImGui_ImplFreeType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src) +{ + ImGui_ImplFreeType_Data* bd = (ImGui_ImplFreeType_Data*)atlas->FontLoaderData; + ImGui_ImplFreeType_FontSrcData* bd_font_data = IM_NEW(ImGui_ImplFreeType_FontSrcData); + IM_ASSERT(src->FontLoaderData == nullptr); + src->FontLoaderData = bd_font_data; + + if (!bd_font_data->InitFont(bd->Library, src, (ImGuiFreeTypeLoaderFlags)atlas->FontLoaderFlags)) + { + IM_DELETE(bd_font_data); + src->FontLoaderData = nullptr; + return false; + } + + return true; +} + +void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) +{ + IM_UNUSED(atlas); + ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; + IM_DELETE(bd_font_data); + src->FontLoaderData = nullptr; +} + +bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) +{ + IM_UNUSED(atlas); + float size = baked->Size; + if (src->MergeMode && src->SizePixels != 0.0f) + size *= (src->SizePixels / baked->ContainerFont->Sources[0]->SizePixels); + + ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; + bd_font_data->BakedLastActivated = baked; + + // We use one FT_Size per (source + baked) combination. + ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src; + IM_ASSERT(bd_baked_data != nullptr); + IM_PLACEMENT_NEW(bd_baked_data) ImGui_ImplFreeType_FontSrcBakedData(); + + FT_New_Size(bd_font_data->FtFace, &bd_baked_data->FtSize); + FT_Activate_Size(bd_baked_data->FtSize); + + // Vuhdo 2017: "I'm not sure how to deal with font sizes properly. As far as I understand, currently ImGui assumes that the 'pixel_height' + // is a maximum height of an any given glyph, i.e. it's the sum of font's ascender and descender. Seems strange to me. + // FT_Set_Pixel_Sizes() doesn't seem to get us the same result." + // (FT_Set_Pixel_Sizes() essentially calls FT_Request_Size() with FT_SIZE_REQUEST_TYPE_NOMINAL) + const float rasterizer_density = src->RasterizerDensity * baked->RasterizerDensity; + FT_Size_RequestRec req; + req.type = (bd_font_data->UserFlags & ImGuiFreeTypeLoaderFlags_Bitmap) ? FT_SIZE_REQUEST_TYPE_NOMINAL : FT_SIZE_REQUEST_TYPE_REAL_DIM; + req.width = 0; + req.height = (uint32_t)(size * 64 * rasterizer_density); + req.horiResolution = 0; + req.vertResolution = 0; + FT_Request_Size(bd_font_data->FtFace, &req); + + // Output + if (src->MergeMode == false) + { + // Read metrics + FT_Size_Metrics metrics = bd_baked_data->FtSize->metrics; + const float scale = 1.0f / rasterizer_density; + baked->Ascent = (float)FT_CEIL(metrics.ascender) * scale; // The pixel extents above the baseline in pixels (typically positive). + baked->Descent = (float)FT_CEIL(metrics.descender) * scale; // The extents below the baseline in pixels (typically negative). + //LineSpacing = (float)FT_CEIL(metrics.height) * scale; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate. + //LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender) * scale; // The spacing in pixels between one row's descent and the next row's ascent. + //MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * scale; // This field gives the maximum horizontal cursor advance for all glyphs in the font. + } + return true; +} + +void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) +{ + IM_UNUSED(atlas); + IM_UNUSED(baked); + IM_UNUSED(src); + ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src; + IM_ASSERT(bd_baked_data != nullptr); + FT_Done_Size(bd_baked_data->FtSize); + bd_baked_data->~ImGui_ImplFreeType_FontSrcBakedData(); // ~IM_PLACEMENT_DELETE() +} + +bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x) +{ + ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; + uint32_t glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint); + if (glyph_index == 0) + return false; + + if (bd_font_data->BakedLastActivated != baked) // <-- could use id + { + // Activate current size + ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src; + FT_Activate_Size(bd_baked_data->FtSize); + bd_font_data->BakedLastActivated = baked; + } + + const FT_Glyph_Metrics* metrics = ImGui_ImplFreeType_LoadGlyph(bd_font_data, codepoint); + if (metrics == nullptr) + return false; + + FT_Face face = bd_font_data->FtFace; + FT_GlyphSlot slot = face->glyph; + const float rasterizer_density = src->RasterizerDensity * baked->RasterizerDensity; + + // Load metrics only mode + const float advance_x = (slot->advance.x / FT_SCALEFACTOR) / rasterizer_density; + if (out_advance_x != NULL) + { + IM_ASSERT(out_glyph == NULL); + *out_advance_x = advance_x; + return true; + } + + // Render glyph into a bitmap (currently held by FreeType) + FT_Render_Mode render_mode = (bd_font_data->UserFlags & ImGuiFreeTypeLoaderFlags_Monochrome) ? FT_RENDER_MODE_MONO : FT_RENDER_MODE_NORMAL; + FT_Error error = FT_Render_Glyph(slot, render_mode); + const FT_Bitmap* ft_bitmap = &slot->bitmap; + if (error != 0 || ft_bitmap == nullptr) + return false; + + const int w = (int)ft_bitmap->width; + const int h = (int)ft_bitmap->rows; + const bool is_visible = (w != 0 && h != 0); + + // Prepare glyph + out_glyph->Codepoint = codepoint; + out_glyph->AdvanceX = advance_x; + + // Pack and retrieve position inside texture atlas + if (is_visible) + { + ImFontAtlasRectId pack_id = ImFontAtlasPackAddRect(atlas, w, h); + if (pack_id == ImFontAtlasRectId_Invalid) + { + // Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?) + IM_ASSERT(pack_id != ImFontAtlasRectId_Invalid && "Out of texture memory."); + return false; + } + ImTextureRect* r = ImFontAtlasPackGetRect(atlas, pack_id); + + // Render pixels to our temporary buffer + atlas->Builder->TempBuffer.resize(w * h * 4); + uint32_t* temp_buffer = (uint32_t*)atlas->Builder->TempBuffer.Data; + ImGui_ImplFreeType_BlitGlyph(ft_bitmap, temp_buffer, w); + + const float ref_size = baked->ContainerFont->Sources[0]->SizePixels; + const float offsets_scale = (ref_size != 0.0f) ? (baked->Size / ref_size) : 1.0f; + float font_off_x = (src->GlyphOffset.x * offsets_scale); + float font_off_y = (src->GlyphOffset.y * offsets_scale) + baked->Ascent; + if (src->PixelSnapH) // Snap scaled offset. This is to mitigate backward compatibility issues for GlyphOffset, but a better design would be welcome. + font_off_x = IM_ROUND(font_off_x); + if (src->PixelSnapV) + font_off_y = IM_ROUND(font_off_y); + float recip_h = 1.0f / rasterizer_density; + float recip_v = 1.0f / rasterizer_density; + + // Register glyph + float glyph_off_x = (float)face->glyph->bitmap_left; + float glyph_off_y = (float)-face->glyph->bitmap_top; + out_glyph->X0 = glyph_off_x * recip_h + font_off_x; + out_glyph->Y0 = glyph_off_y * recip_v + font_off_y; + out_glyph->X1 = (glyph_off_x + w) * recip_h + font_off_x; + out_glyph->Y1 = (glyph_off_y + h) * recip_v + font_off_y; + out_glyph->Visible = true; + out_glyph->Colored = (ft_bitmap->pixel_mode == FT_PIXEL_MODE_BGRA); + out_glyph->PackId = pack_id; + ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, out_glyph, r, (const unsigned char*)temp_buffer, ImTextureFormat_RGBA32, w * 4); + } + + return true; +} + +bool ImGui_ImplFreetype_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint) +{ + IM_UNUSED(atlas); + ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; + int glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint); + return glyph_index != 0; +} + +const ImFontLoader* ImGuiFreeType::GetFontLoader() +{ + static ImFontLoader loader; + loader.Name = "FreeType"; + loader.LoaderInit = ImGui_ImplFreeType_LoaderInit; + loader.LoaderShutdown = ImGui_ImplFreeType_LoaderShutdown; + loader.FontSrcInit = ImGui_ImplFreeType_FontSrcInit; + loader.FontSrcDestroy = ImGui_ImplFreeType_FontSrcDestroy; + loader.FontSrcContainsGlyph = ImGui_ImplFreetype_FontSrcContainsGlyph; + loader.FontBakedInit = ImGui_ImplFreeType_FontBakedInit; + loader.FontBakedDestroy = ImGui_ImplFreeType_FontBakedDestroy; + loader.FontBakedLoadGlyph = ImGui_ImplFreeType_FontBakedLoadGlyph; + loader.FontBakedSrcLoaderDataSize = sizeof(ImGui_ImplFreeType_FontSrcBakedData); + return &loader; } void ImGuiFreeType::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data) @@ -851,6 +619,22 @@ void ImGuiFreeType::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* u GImGuiFreeTypeAllocatorUserData = user_data; } +bool ImGuiFreeType::DebugEditFontLoaderFlags(unsigned int* p_font_loader_flags) +{ + bool edited = false; + edited |= ImGui::CheckboxFlags("NoHinting", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_NoHinting); + edited |= ImGui::CheckboxFlags("NoAutoHint", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_NoAutoHint); + edited |= ImGui::CheckboxFlags("ForceAutoHint",p_font_loader_flags, ImGuiFreeTypeLoaderFlags_ForceAutoHint); + edited |= ImGui::CheckboxFlags("LightHinting", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_LightHinting); + edited |= ImGui::CheckboxFlags("MonoHinting", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_MonoHinting); + edited |= ImGui::CheckboxFlags("Bold", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_Bold); + edited |= ImGui::CheckboxFlags("Oblique", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_Oblique); + edited |= ImGui::CheckboxFlags("Monochrome", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_Monochrome); + edited |= ImGui::CheckboxFlags("LoadColor", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_LoadColor); + edited |= ImGui::CheckboxFlags("Bitmap", p_font_loader_flags, ImGuiFreeTypeLoaderFlags_Bitmap); + return edited; +} + #ifdef IMGUI_ENABLE_FREETYPE_LUNASVG // For more details, see https://gitlab.freedesktop.org/freetype/freetype-demos/-/blob/master/src/rsvg-port.c // The original code from the demo is licensed under CeCILL-C Free Software License Agreement (https://gitlab.freedesktop.org/freetype/freetype/-/blob/master/LICENSE.TXT) @@ -882,8 +666,12 @@ static FT_Error ImGuiLunasvgPortRender(FT_GlyphSlot slot, FT_Pointer* _state) // rows is height, pitch (or stride) equals to width * sizeof(int32) lunasvg::Bitmap bitmap((uint8_t*)slot->bitmap.buffer, slot->bitmap.width, slot->bitmap.rows, slot->bitmap.pitch); +#if LUNASVG_VERSION_MAJOR >= 3 + state->svg->render(bitmap, state->matrix); // state->matrix is already scaled and translated +#else state->svg->setMatrix(state->svg->matrix().identity()); // Reset the svg matrix to the default value state->svg->render(bitmap, state->matrix); // state->matrix is already scaled and translated +#endif state->err = FT_Err_Ok; return state->err; } @@ -906,7 +694,11 @@ static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_ return state->err; } +#if LUNASVG_VERSION_MAJOR >= 3 + lunasvg::Box box = state->svg->boundingBox(); +#else lunasvg::Box box = state->svg->box(); +#endif double scale = std::min(metrics.x_ppem / box.w, metrics.y_ppem / box.h); double xx = (double)document->transform.xx / (1 << 16); double xy = -(double)document->transform.xy / (1 << 16); @@ -915,6 +707,15 @@ static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_ double x0 = (double)document->delta.x / 64 * box.w / metrics.x_ppem; double y0 = -(double)document->delta.y / 64 * box.h / metrics.y_ppem; +#if LUNASVG_VERSION_MAJOR >= 3 + // Scale, transform and pre-translate the matrix for the rendering step + state->matrix = lunasvg::Matrix::translated(-box.x, -box.y); + state->matrix.multiply(lunasvg::Matrix(xx, xy, yx, yy, x0, y0)); + state->matrix.scale(scale, scale); + + // Apply updated transformation to the bounding box + box.transform(state->matrix); +#else // Scale and transform, we don't translate the svg yet state->matrix.identity(); state->matrix.scale(scale, scale); @@ -926,6 +727,7 @@ static FT_Error ImGuiLunasvgPortPresetSlot(FT_GlyphSlot slot, FT_Bool cache, FT_ // Get the box again after the transformation box = state->svg->box(); +#endif // Calculate the bitmap size slot->bitmap_left = FT_Int(box.x); diff --git a/lib/third_party/imgui/imnodes/source/imnodes.cpp b/lib/third_party/imgui/imnodes/source/imnodes.cpp index a08a77927..8f406de36 100644 --- a/lib/third_party/imgui/imnodes/source/imnodes.cpp +++ b/lib/third_party/imgui/imnodes/source/imnodes.cpp @@ -354,7 +354,7 @@ void ImDrawListGrowChannels(ImDrawList* draw_list, const int num_channels) { ImDrawCmd draw_cmd; draw_cmd.ClipRect = draw_list->_ClipRectStack.back(); - draw_cmd.TextureId = draw_list->_TextureIdStack.back(); + draw_cmd.TexRef = draw_list->_TextureStack.back(); channel._CmdBuffer.push_back(draw_cmd); } } diff --git a/lib/third_party/imgui/implot/include/implot.h b/lib/third_party/imgui/implot/include/implot.h index 305433123..e15ce3976 100644 --- a/lib/third_party/imgui/implot/include/implot.h +++ b/lib/third_party/imgui/implot/include/implot.h @@ -912,7 +912,11 @@ IMPLOT_TMP void PlotDigital(const char* label_id, const T* xs, const T* ys, int IMPLOT_API void PlotDigitalG(const char* label_id, ImPlotGetter getter, void* data, int count, ImPlotDigitalFlags flags=0); // Plots an axis-aligned image. #bounds_min/bounds_max are in plot coordinates (y-up) and #uv0/uv1 are in texture coordinates (y-down). -IMPLOT_API void PlotImage(const char* label_id, ImTextureID user_texture_id, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max, const ImVec2& uv0=ImVec2(0,0), const ImVec2& uv1=ImVec2(1,1), const ImVec4& tint_col=ImVec4(1,1,1,1), ImPlotImageFlags flags=0); +#ifdef IMGUI_HAS_TEXTURES + IMPLOT_API void PlotImage(const char* label_id, ImTextureRef tex_ref, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& tint_col = ImVec4(1, 1, 1, 1), ImPlotImageFlags flags = 0); +#else + IMPLOT_API void PlotImage(const char* label_id, ImTextureID tex_ref, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max, const ImVec2& uv0=ImVec2(0,0), const ImVec2& uv1=ImVec2(1,1), const ImVec4& tint_col=ImVec4(1,1,1,1), ImPlotImageFlags flags=0); +#endif // Plots a centered text label at point x,y with an optional pixel offset. Text color can be changed with ImPlot::PushStyleColor(ImPlotCol_InlayText, ...). IMPLOT_API void PlotText(const char* text, double x, double y, const ImVec2& pix_offset=ImVec2(0,0), ImPlotTextFlags flags=0); diff --git a/lib/third_party/imgui/implot/source/implot.cpp b/lib/third_party/imgui/implot/source/implot.cpp index 2a5d66c4b..3a84e25e4 100644 --- a/lib/third_party/imgui/implot/source/implot.cpp +++ b/lib/third_party/imgui/implot/source/implot.cpp @@ -339,11 +339,18 @@ void AddTextVertical(ImDrawList *DrawList, ImVec2 pos, ImU32 col, const char *te if (!text_end) text_end = text_begin + strlen(text_begin); ImGuiContext& g = *GImGui; + +#ifdef IMGUI_HAS_TEXTURES + ImFontBaked* font = g.Font->GetFontBaked(g.FontSize); + const float scale = g.FontSize / font->Size; +#else ImFont* font = g.Font; + const float scale = g.FontSize / font->FontSize; +#endif + // Align to be pixel perfect pos.x = ImFloor(pos.x); pos.y = ImFloor(pos.y); - const float scale = g.FontSize / font->FontSize; const char* s = text_begin; int chars_exp = (int)(text_end - s); int chars_rnd = 0; @@ -3064,7 +3071,11 @@ void EndPlot() { ImGui::SetKeyOwner(ImGuiKey_MouseWheelY, plot.Items.ID); if (IO.MouseWheel != 0.0f) { ImVec2 max_step = legend.Rect.GetSize() * 0.67f; +#if IMGUI_VERSION_NUM < 19172 float font_size = ImGui::GetCurrentWindow()->CalcFontSize(); +#else + float font_size = ImGui::GetCurrentWindow()->FontRefSize; +#endif float scroll_step = ImFloor(ImMin(2 * font_size, max_step.x)); legend.Scroll.x += scroll_step * IO.MouseWheel; legend.Scroll.y += scroll_step * IO.MouseWheel; @@ -3583,7 +3594,11 @@ void EndSubplots() { ImGui::SetKeyOwner(ImGuiKey_MouseWheelY, subplot.Items.ID); if (IO.MouseWheel != 0.0f) { ImVec2 max_step = legend.Rect.GetSize() * 0.67f; +#if IMGUI_VERSION_NUM < 19172 float font_size = ImGui::GetCurrentWindow()->CalcFontSize(); +#else + float font_size = ImGui::GetCurrentWindow()->FontRefSize; +#endif float scroll_step = ImFloor(ImMin(2 * font_size, max_step.x)); legend.Scroll.x += scroll_step * IO.MouseWheel; legend.Scroll.y += scroll_step * IO.MouseWheel; diff --git a/lib/third_party/imgui/implot/source/implot_demo.cpp b/lib/third_party/imgui/implot/source/implot_demo.cpp index 79064fdf2..a993ba85d 100644 --- a/lib/third_party/imgui/implot/source/implot_demo.cpp +++ b/lib/third_party/imgui/implot/source/implot_demo.cpp @@ -867,7 +867,14 @@ void Demo_Images() { ImGui::SliderFloat2("UV1", &uv1.x, -2, 2, "%.1f"); ImGui::ColorEdit4("Tint",&tint.x); if (ImPlot::BeginPlot("##image")) { - ImPlot::PlotImage("my image",ImGui::GetIO().Fonts->TexID, bmin, bmax, uv0, uv1, tint); +#ifdef IMGUI_HAS_TEXTURES + // We use the font atlas ImTextureRef for this demo, but in your real code when you submit + // an image that you have loaded yourself, you would normally have a ImTextureID which works + // just as well (as ImTextureRef can be constructed from ImTextureID). + ImPlot::PlotImage("my image", ImGui::GetIO().Fonts->TexRef, bmin, bmax, uv0, uv1, tint); +#else + ImPlot::PlotImage("my image", ImGui::GetIO().Fonts->TexID, bmin, bmax, uv0, uv1, tint); +#endif ImPlot::EndPlot(); } } diff --git a/lib/third_party/imgui/implot/source/implot_items.cpp b/lib/third_party/imgui/implot/source/implot_items.cpp index 91c71d829..9430f63da 100644 --- a/lib/third_party/imgui/implot/source/implot_items.cpp +++ b/lib/third_party/imgui/implot/source/implot_items.cpp @@ -2750,15 +2750,19 @@ void PlotDigitalG(const char* label_id, ImPlotGetter getter_func, void* data, in // [SECTION] PlotImage //----------------------------------------------------------------------------- -void PlotImage(const char* label_id, ImTextureID user_texture_id, const ImPlotPoint& bmin, const ImPlotPoint& bmax, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, ImPlotImageFlags) { - if (BeginItemEx(label_id, FitterRect(bmin,bmax))) { +#ifdef IMGUI_HAS_TEXTURES + void PlotImage(const char* label_id, ImTextureRef tex_ref, const ImPlotPoint& bmin, const ImPlotPoint& bmax, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, ImPlotImageFlags) { +#else + void PlotImage(const char* label_id, ImTextureID tex_ref, const ImPlotPoint& bmin, const ImPlotPoint& bmax, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, ImPlotImageFlags) { +#endif + if (BeginItemEx(label_id, FitterRect(bmin,bmax))) { ImU32 tint_col32 = ImGui::ColorConvertFloat4ToU32(tint_col); GetCurrentItem()->Color = tint_col32; ImDrawList& draw_list = *GetPlotDrawList(); ImVec2 p1 = PlotToPixels(bmin.x, bmax.y,IMPLOT_AUTO,IMPLOT_AUTO); ImVec2 p2 = PlotToPixels(bmax.x, bmin.y,IMPLOT_AUTO,IMPLOT_AUTO); PushPlotClipRect(); - draw_list.AddImage(user_texture_id, p1, p2, uv0, uv1, tint_col32); + draw_list.AddImage(tex_ref, p1, p2, uv0, uv1, tint_col32); PopPlotClipRect(); EndItem(); } diff --git a/lib/third_party/imgui/implot3d/include/implot3d.h b/lib/third_party/imgui/implot3d/include/implot3d.h index 7abaa179e..d0e9f08e6 100644 --- a/lib/third_party/imgui/implot3d/include/implot3d.h +++ b/lib/third_party/imgui/implot3d/include/implot3d.h @@ -1,5 +1,5 @@ //-------------------------------------------------- -// ImPlot3D v0.1 +// ImPlot3D v0.3 WIP // implot3d.h // Date: 2024-11-16 // Author: Breno Cunha Queiroz (brenocq.com) @@ -45,7 +45,8 @@ #define IMPLOT3D_API #endif -#define IMPLOT3D_VERSION "0.1" // ImPlot3D version +#define IMPLOT3D_VERSION "0.3 WIP" // ImPlot3D version +#define IMPLOT3D_VERSION_NUM 300 // Integer encoded version #define IMPLOT3D_AUTO -1 // Deduce variable automatically #define IMPLOT3D_AUTO_COL ImVec4(0, 0, 0, -1) // Deduce color automatically #define IMPLOT3D_TMP template IMPLOT3D_API @@ -83,9 +84,16 @@ typedef int ImPlot3DTriangleFlags; // -> ImPlot3DTriangleFlags_ // Flags: Triang typedef int ImPlot3DQuadFlags; // -> ImPlot3DQuadFlags_ // Flags: QuadFplot flags typedef int ImPlot3DSurfaceFlags; // -> ImPlot3DSurfaceFlags_ // Flags: Surface plot flags typedef int ImPlot3DMeshFlags; // -> ImPlot3DMeshFlags_ // Flags: Mesh plot flags +typedef int ImPlot3DImageFlags; // -> ImPlot3DImageFlags_ // Flags: Image plot flags typedef int ImPlot3DLegendFlags; // -> ImPlot3DLegendFlags_ // Flags: Legend flags typedef int ImPlot3DAxisFlags; // -> ImPlot3DAxisFlags_ // Flags: Axis flags +// Fallback for ImGui versions before v1.92: define ImTextureRef as ImTextureID +// You can `#define IMPLOT3D_NO_IMTEXTUREREF` to avoid this fallback +#if !defined(IMGUI_HAS_TEXTURES) && !defined(IMPLOT3D_NO_IMTEXTUREREF) +typedef ImTextureID ImTextureRef; +#endif + //----------------------------------------------------------------------------- // [SECTION] Flags & Enumerations //----------------------------------------------------------------------------- @@ -195,6 +203,9 @@ enum ImPlot3DTriangleFlags_ { ImPlot3DTriangleFlags_None = 0, // Default ImPlot3DTriangleFlags_NoLegend = ImPlot3DItemFlags_NoLegend, ImPlot3DTriangleFlags_NoFit = ImPlot3DItemFlags_NoFit, + ImPlot3DTriangleFlags_NoLines = 1 << 10, // No lines will be rendered + ImPlot3DTriangleFlags_NoFill = 1 << 11, // No fill will be rendered + ImPlot3DTriangleFlags_NoMarkers = 1 << 12, // No markers will be rendered }; // Flags for PlotQuad @@ -202,6 +213,9 @@ enum ImPlot3DQuadFlags_ { ImPlot3DQuadFlags_None = 0, // Default ImPlot3DQuadFlags_NoLegend = ImPlot3DItemFlags_NoLegend, ImPlot3DQuadFlags_NoFit = ImPlot3DItemFlags_NoFit, + ImPlot3DQuadFlags_NoLines = 1 << 10, // No lines will be rendered + ImPlot3DQuadFlags_NoFill = 1 << 11, // No fill will be rendered + ImPlot3DQuadFlags_NoMarkers = 1 << 12, // No markers will be rendered }; // Flags for PlotSurface @@ -209,6 +223,9 @@ enum ImPlot3DSurfaceFlags_ { ImPlot3DSurfaceFlags_None = 0, // Default ImPlot3DSurfaceFlags_NoLegend = ImPlot3DItemFlags_NoLegend, ImPlot3DSurfaceFlags_NoFit = ImPlot3DItemFlags_NoFit, + ImPlot3DSurfaceFlags_NoLines = 1 << 10, // No lines will be rendered + ImPlot3DSurfaceFlags_NoFill = 1 << 11, // No fill will be rendered + ImPlot3DSurfaceFlags_NoMarkers = 1 << 12, // No markers will be rendered }; // Flags for PlotMesh @@ -216,6 +233,16 @@ enum ImPlot3DMeshFlags_ { ImPlot3DMeshFlags_None = 0, // Default ImPlot3DMeshFlags_NoLegend = ImPlot3DItemFlags_NoLegend, ImPlot3DMeshFlags_NoFit = ImPlot3DItemFlags_NoFit, + ImPlot3DMeshFlags_NoLines = 1 << 10, // No lines will be rendered + ImPlot3DMeshFlags_NoFill = 1 << 11, // No fill will be rendered + ImPlot3DMeshFlags_NoMarkers = 1 << 12, // No markers will be rendered +}; + +// Flags for PlotImage +enum ImPlot3DImageFlags_ { + ImPlot3DImageFlags_None = 0, // Default + ImPlot3DImageFlags_NoLegend = ImPlot3DItemFlags_NoLegend, + ImPlot3DImageFlags_NoFit = ImPlot3DItemFlags_NoFit, }; // Flags for legends @@ -250,6 +277,7 @@ enum ImPlot3DAxisFlags_ { ImPlot3DAxisFlags_LockMax = 1 << 5, // The axis maximum value will be locked when panning/zooming ImPlot3DAxisFlags_AutoFit = 1 << 6, // Axis will be auto-fitting to data extents ImPlot3DAxisFlags_Invert = 1 << 7, // The axis will be inverted + ImPlot3DAxisFlags_PanStretch = 1 << 8, // Panning in a locked or constrained state will cause the axis to stretch if possible ImPlot3DAxisFlags_Lock = ImPlot3DAxisFlags_LockMin | ImPlot3DAxisFlags_LockMax, ImPlot3DAxisFlags_NoDecorations = ImPlot3DAxisFlags_NoLabel | ImPlot3DAxisFlags_NoGridLines | ImPlot3DAxisFlags_NoTickLabels, }; @@ -362,21 +390,44 @@ IMPLOT3D_API void SetupAxis(ImAxis3D axis, const char* label = nullptr, ImPlot3D IMPLOT3D_API void SetupAxisLimits(ImAxis3D axis, double v_min, double v_max, ImPlot3DCond cond = ImPlot3DCond_Once); -IMPLOT3D_API void SetupAxisFormat(ImAxis3D idx, ImPlot3DFormatter formatter, void* data = nullptr); +IMPLOT3D_API void SetupAxisFormat(ImAxis3D axis, ImPlot3DFormatter formatter, void* data = nullptr); // Sets an axis' ticks and optionally the labels. To keep the default ticks, set #keep_default=true IMPLOT3D_API void SetupAxisTicks(ImAxis3D axis, const double* values, int n_ticks, const char* const labels[] = nullptr, bool keep_default = false); // Sets an axis' ticks and optionally the labels for the next plot. To keep the default ticks, set #keep_default=true -IMPLOT3D_API void SetupAxisTicks(ImAxis3D axis, double v_min, double v_max, int n_ticks, const char* const labels[] = nullptr, bool keep_default = false); +IMPLOT3D_API void SetupAxisTicks(ImAxis3D axis, double v_min, double v_max, int n_ticks, const char* const labels[] = nullptr, + bool keep_default = false); + +// Sets an axis' limits constraints +IMPLOT3D_API void SetupAxisLimitsConstraints(ImAxis3D axis, double v_min, double v_max); + +// Sets an axis' zoom constraints +IMPLOT3D_API void SetupAxisZoomConstraints(ImAxis3D axis, double z_min, double z_max); // Sets the label and/or flags for primary X/Y/Z axes (shorthand for three calls to SetupAxis) -IMPLOT3D_API void SetupAxes(const char* x_label, const char* y_label, const char* z_label, ImPlot3DAxisFlags x_flags = 0, ImPlot3DAxisFlags y_flags = 0, ImPlot3DAxisFlags z_flags = 0); +IMPLOT3D_API void SetupAxes(const char* x_label, const char* y_label, const char* z_label, ImPlot3DAxisFlags x_flags = 0, + ImPlot3DAxisFlags y_flags = 0, ImPlot3DAxisFlags z_flags = 0); -// Sets the X/Y/Z axes range limits. If ImPlotCond_Always is used, the axes limits will be locked (shorthand for two calls to SetupAxisLimits) -IMPLOT3D_API void SetupAxesLimits(double x_min, double x_max, double y_min, double y_max, double z_min, double z_max, ImPlot3DCond cond = ImPlot3DCond_Once); +// Sets the X/Y/Z axes range limits. If ImPlot3DCond_Always is used, the axes limits will be locked (shorthand for two calls to SetupAxisLimits) +IMPLOT3D_API void SetupAxesLimits(double x_min, double x_max, double y_min, double y_max, double z_min, double z_max, + ImPlot3DCond cond = ImPlot3DCond_Once); -// Sets the plot box X/Y/Z scale. A scale of 1.0 is the default. Values greater than 1.0 enlarge the plot, while values between 0.0 and 1.0 shrink it. +// Sets the plot box rotation given the elevation and azimuth angles in degrees. If ImPlot3DCond_Always is used, the rotation will be locked +IMPLOT3D_API void SetupBoxRotation(float elevation, float azimuth, bool animate = false, ImPlot3DCond cond = ImPlot3DCond_Once); + +// Sets the plot box rotation given a quaternion. If ImPlot3DCond_Always is used, the rotation will be locked +IMPLOT3D_API void SetupBoxRotation(ImPlot3DQuat rotation, bool animate = false, ImPlot3DCond cond = ImPlot3DCond_Once); + +// Sets the plot box initial rotation given the elevation and azimuth angles in degrees. The initial rotation is the rotation the plot goes back to +// when a left mouse button double click happens +IMPLOT3D_API void SetupBoxInitialRotation(float elevation, float azimuth); + +// Sets the plot box initial rotation given a quaternion. The initial rotation is the rotation the plot goes back to when a left mouse button double +// click happens +IMPLOT3D_API void SetupBoxInitialRotation(ImPlot3DQuat rotation); + +// Sets the plot box X/Y/Z scale. A scale of 1.0 is the default. Values greater than 1.0 enlarge the plot, while values between 0.0 and 1.0 shrink it IMPLOT3D_API void SetupBoxScale(float x, float y, float z); IMPLOT3D_API void SetupLegend(ImPlot3DLocation location, ImPlot3DLegendFlags flags = 0); @@ -385,18 +436,46 @@ IMPLOT3D_API void SetupLegend(ImPlot3DLocation location, ImPlot3DLegendFlags fla // [SECTION] Plot Items //----------------------------------------------------------------------------- -IMPLOT3D_TMP void PlotScatter(const char* label_id, const T* xs, const T* ys, const T* zs, int count, ImPlot3DScatterFlags flags = 0, int offset = 0, int stride = sizeof(T)); +IMPLOT3D_TMP void PlotScatter(const char* label_id, const T* xs, const T* ys, const T* zs, int count, ImPlot3DScatterFlags flags = 0, int offset = 0, + int stride = sizeof(T)); -IMPLOT3D_TMP void PlotLine(const char* label_id, const T* xs, const T* ys, const T* zs, int count, ImPlot3DLineFlags flags = 0, int offset = 0, int stride = sizeof(T)); +IMPLOT3D_TMP void PlotLine(const char* label_id, const T* xs, const T* ys, const T* zs, int count, ImPlot3DLineFlags flags = 0, int offset = 0, + int stride = sizeof(T)); -IMPLOT3D_TMP void PlotTriangle(const char* label_id, const T* xs, const T* ys, const T* zs, int count, ImPlot3DTriangleFlags flags = 0, int offset = 0, int stride = sizeof(T)); +IMPLOT3D_TMP void PlotTriangle(const char* label_id, const T* xs, const T* ys, const T* zs, int count, ImPlot3DTriangleFlags flags = 0, + int offset = 0, int stride = sizeof(T)); -IMPLOT3D_TMP void PlotQuad(const char* label_id, const T* xs, const T* ys, const T* zs, int count, ImPlot3DQuadFlags flags = 0, int offset = 0, int stride = sizeof(T)); +IMPLOT3D_TMP void PlotQuad(const char* label_id, const T* xs, const T* ys, const T* zs, int count, ImPlot3DQuadFlags flags = 0, int offset = 0, + int stride = sizeof(T)); -// Plot the surface defined by a grid of vertices. The grid is defined by the x and y arrays, and the z array contains the height of each vertex. A total of x_count * y_count vertices are expected for each array. Leave #scale_min and #scale_max both at 0 for automatic color scaling, or set them to a predefined range. -IMPLOT3D_TMP void PlotSurface(const char* label_id, const T* xs, const T* ys, const T* zs, int x_count, int y_count, double scale_min = 0.0, double scale_max = 0.0, ImPlot3DSurfaceFlags flags = 0, int offset = 0, int stride = sizeof(T)); +// Plot the surface defined by a grid of vertices. The grid is defined by the x and y arrays, and the z array contains the height of each vertex. A +// total of x_count * y_count vertices are expected for each array. Leave #scale_min and #scale_max both at 0 for automatic color scaling, or set them +// to a predefined range +IMPLOT3D_TMP void PlotSurface(const char* label_id, const T* xs, const T* ys, const T* zs, int x_count, int y_count, double scale_min = 0.0, + double scale_max = 0.0, ImPlot3DSurfaceFlags flags = 0, int offset = 0, int stride = sizeof(T)); -IMPLOT3D_API void PlotMesh(const char* label_id, const ImPlot3DPoint* vtx, const unsigned int* idx, int vtx_count, int idx_count, ImPlot3DMeshFlags flags = 0); +IMPLOT3D_API void PlotMesh(const char* label_id, const ImPlot3DPoint* vtx, const unsigned int* idx, int vtx_count, int idx_count, + ImPlot3DMeshFlags flags = 0); + +// Plots a rectangular image in 3D defined by its center and two direction vectors (axes). +// #center is the center of the rectangle in plot coordinates. +// #axis_u and #axis_v define the local axes and half-extents of the rectangle in 3D space. +// The rectangle is formed by moving from the center along ±axis_u and ±axis_v. +// #uv0 and #uv1 define the texture mapping. +// #tint_col can be used to tint the image. +IMPLOT3D_API void PlotImage(const char* label_id, ImTextureRef tex_ref, const ImPlot3DPoint& center, const ImPlot3DPoint& axis_u, + const ImPlot3DPoint& axis_v, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), + const ImVec4& tint_col = ImVec4(1, 1, 1, 1), ImPlot3DImageFlags flags = 0); + +// Plots an image using four arbitrary 3D points that define a quad in space. +// Each corner (p0 to p3) corresponds to a corner in the image, and #uv0 to #uv3 are the texture coordinates for each. +// This overload allows full control over orientation, shape, and distortion. +// Note: The quad is internally split into two triangles, so non-rectangular quads may produce rendering artifacts +// since distortion is interpolated per triangle rather than over the full quad. +IMPLOT3D_API void PlotImage(const char* label_id, ImTextureRef tex_ref, const ImPlot3DPoint& p0, const ImPlot3DPoint& p1, const ImPlot3DPoint& p2, + const ImPlot3DPoint& p3, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 0), + const ImVec2& uv2 = ImVec2(1, 1), const ImVec2& uv3 = ImVec2(0, 1), const ImVec4& tint_col = ImVec4(1, 1, 1, 1), + ImPlot3DImageFlags flags = 0); // Plots a centered text label at point x,y,z. It is possible to set the text angle in radians and offset in pixels IMPLOT3D_API void PlotText(const char* text, float x, float y, float z, float angle = 0.0f, const ImVec2& pix_offset = ImVec2(0, 0)); @@ -430,6 +509,7 @@ IMPLOT3D_API ImDrawList* GetPlotDrawList(); // Get current style IMPLOT3D_API ImPlot3DStyle& GetStyle(); +IMPLOT3D_API void SetStyle(const ImPlot3DStyle& style); // Set color styles IMPLOT3D_API void StyleColorsAuto(ImPlot3DStyle* dst = nullptr); // Set colors with ImGui style @@ -457,7 +537,8 @@ IMPLOT3D_API void SetNextLineStyle(const ImVec4& col = IMPLOT3D_AUTO_COL, float // Set the fill color for the next item only IMPLOT3D_API void SetNextFillStyle(const ImVec4& col = IMPLOT3D_AUTO_COL, float alpha_mod = IMPLOT3D_AUTO); // Set the marker style for the next item only -IMPLOT3D_API void SetNextMarkerStyle(ImPlot3DMarker marker = IMPLOT3D_AUTO, float size = IMPLOT3D_AUTO, const ImVec4& fill = IMPLOT3D_AUTO_COL, float weight = IMPLOT3D_AUTO, const ImVec4& outline = IMPLOT3D_AUTO_COL); +IMPLOT3D_API void SetNextMarkerStyle(ImPlot3DMarker marker = IMPLOT3D_AUTO, float size = IMPLOT3D_AUTO, const ImVec4& fill = IMPLOT3D_AUTO_COL, + float weight = IMPLOT3D_AUTO, const ImVec4& outline = IMPLOT3D_AUTO_COL); // Get color IMPLOT3D_API ImVec4 GetStyleColorVec4(ImPlot3DCol idx); @@ -492,9 +573,11 @@ IMPLOT3D_API const char* GetColormapName(ImPlot3DColormap cmap); // Returns an index number for a colormap given a valid string name. Returns -1 if name is invalid IMPLOT3D_API ImPlot3DColormap GetColormapIndex(const char* name); -// Temporarily switch to one of the built-in (i.e. ImPlot3DColormap_XXX) or user-added colormaps (i.e. a return value of AddColormap). Don't forget to call PopColormap! +// Temporarily switch to one of the built-in (i.e. ImPlot3DColormap_XXX) or user-added colormaps (i.e. a return value of AddColormap). Don't forget to +// call PopColormap! IMPLOT3D_API void PushColormap(ImPlot3DColormap cmap); -// Push a colormap by string name. Use built-in names such as "Default", "Deep", "Jet", etc. or a string you provided to AddColormap. Don't forget to call PopColormap! +// Push a colormap by string name. Use built-in names such as "Default", "Deep", "Jet", etc. or a string you provided to AddColormap. Don't forget to +// call PopColormap! IMPLOT3D_API void PushColormap(const char* name); // Undo temporary colormap modification(s). Undo multiple pushes at once by increasing count IMPLOT3D_API void PopColormap(int count = 1); @@ -517,10 +600,15 @@ IMPLOT3D_API ImVec4 SampleColormap(float t, ImPlot3DColormap cmap = IMPLOT3D_AUT // Shows the ImPlot3D demo window IMPLOT3D_API void ShowDemoWindow(bool* p_open = nullptr); +// Shows all ImPlot3D demos, without enclosing window +IMPLOT3D_API void ShowAllDemos(); // Shows ImPlot3D style editor block (not a window) IMPLOT3D_API void ShowStyleEditor(ImPlot3DStyle* ref = nullptr); +// Shows ImPlot3D metrics/debug information window. +IMPLOT3D_API void ShowMetricsWindow(bool* p_popen = nullptr); + } // namespace ImPlot3D //----------------------------------------------------------------------------- @@ -591,7 +679,8 @@ struct ImPlot3DPoint { IMPLOT3D_API bool IsNaN() const; #ifdef IMPLOT3D_POINT_CLASS_EXTRA - IMPLOT3D_POINT_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImPlot3DPoint + IMPLOT3D_POINT_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math + // types and ImPlot3DPoint #endif }; @@ -669,6 +758,9 @@ struct ImPlot3DQuat { // Set quaternion from two vectors IMPLOT3D_API static ImPlot3DQuat FromTwoVectors(const ImPlot3DPoint& v0, const ImPlot3DPoint& v1); + // Set quaternion given elevation and azimuth angles in radians + IMPLOT3D_API static ImPlot3DQuat FromElAz(float elevation, float azimuth); + // Get quaternion length IMPLOT3D_API float Length() const; @@ -701,7 +793,8 @@ struct ImPlot3DQuat { IMPLOT3D_API float Dot(const ImPlot3DQuat& rhs) const; #ifdef IMPLOT3D_QUAT_CLASS_EXTRA - IMPLOT3D_QUAT_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImPlot3DQuat + IMPLOT3D_QUAT_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math + // types and ImPlot3DQuat #endif }; @@ -727,10 +820,13 @@ struct ImPlot3DStyle { ImVec2 LegendSpacing; // Spacing between legend entries // Colors ImVec4 Colors[ImPlot3DCol_COUNT]; + inline ImVec4 GetColor(ImPlot3DCol idx) const { return Colors[idx]; } + inline void SetColor(ImPlot3DCol idx, const ImVec4& col) { Colors[idx] = col; } // Colormap ImPlot3DColormap Colormap; // The current colormap. Set this to either an ImPlot3DColormap_ enum or an index returned by AddColormap // Constructor IMPLOT3D_API ImPlot3DStyle(); + ImPlot3DStyle(const ImPlot3DStyle& other) = default; }; //----------------------------------------------------------------------------- diff --git a/lib/third_party/imgui/implot3d/include/implot3d_internal.h b/lib/third_party/imgui/implot3d/include/implot3d_internal.h index 859e43d4a..d1a22be5e 100644 --- a/lib/third_party/imgui/implot3d/include/implot3d_internal.h +++ b/lib/third_party/imgui/implot3d/include/implot3d_internal.h @@ -1,5 +1,5 @@ //-------------------------------------------------- -// ImPlot3D v0.1 +// ImPlot3D v0.3 WIP // implot3d_internal.h // Date: 2024-11-17 // Author: Breno Cunha Queiroz (brenocq.com) @@ -53,13 +53,10 @@ namespace ImPlot3D { // Computes the common (base-10) logarithm static inline float ImLog10(float x) { return log10f(x); } // Returns true if flag is set -template -static inline bool ImHasFlag(TSet set, TFlag flag) { return (set & flag) == flag; } +template static inline bool ImHasFlag(TSet set, TFlag flag) { return (set & flag) == flag; } // Flips a flag in a flagset -template -static inline void ImFlipFlag(TSet& set, TFlag flag) { ImHasFlag(set, flag) ? set &= ~flag : set |= flag; } -template -static inline T ImRemap01(T x, T x0, T x1) { return (x - x0) / (x1 - x0); } +template static inline void ImFlipFlag(TSet& set, TFlag flag) { ImHasFlag(set, flag) ? set &= ~flag : set |= flag; } +template static inline T ImRemap01(T x, T x0, T x1) { return (x1 - x0) ? ((x - x0) / (x1 - x0)) : 0; } // Returns true if val is NAN static inline bool ImNan(float val) { return isnan(val); } // Returns true if val is NAN or INFINITY @@ -67,14 +64,13 @@ static inline bool ImNanOrInf(float val) { return !(val >= -FLT_MAX && val <= FL // Turns NANs to 0s static inline double ImConstrainNan(float val) { return ImNan(val) ? 0 : val; } // Turns infinity to floating point maximums -static inline double ImConstrainInf(double val) { return val >= FLT_MAX ? FLT_MAX : val <= -FLT_MAX ? -FLT_MAX - : val; } +static inline double ImConstrainInf(double val) { return val >= FLT_MAX ? FLT_MAX : val <= -FLT_MAX ? -FLT_MAX : val; } // True if two numbers are approximately equal using units in the last place. -static inline bool ImAlmostEqual(double v1, double v2, int ulp = 2) { return ImAbs(v1 - v2) < FLT_EPSILON * ImAbs(v1 + v2) * ulp || ImAbs(v1 - v2) < FLT_MIN; } -// Set alpha channel of 32-bit color from float in range [0.0 1.0] -static inline ImU32 ImAlphaU32(ImU32 col, float alpha) { - return col & ~((ImU32)((1.0f - alpha) * 255) << IM_COL32_A_SHIFT); +static inline bool ImAlmostEqual(double v1, double v2, int ulp = 2) { + return ImAbs(v1 - v2) < FLT_EPSILON * ImAbs(v1 + v2) * ulp || ImAbs(v1 - v2) < FLT_MIN; } +// Set alpha channel of 32-bit color from float in range [0.0 1.0] +static inline ImU32 ImAlphaU32(ImU32 col, float alpha) { return col & ~((ImU32)((1.0f - alpha) * 255) << IM_COL32_A_SHIFT); } // Mix color a and b by factor s in [0 256] static inline ImU32 ImMixU32(ImU32 a, ImU32 b, ImU32 s) { #ifdef IMPLOT3D_MIX64 @@ -98,8 +94,7 @@ static inline ImU32 ImMixU32(ImU32 a, ImU32 b, ImU32 s) { } // Fills a buffer with n samples linear interpolated from vmin to vmax -template -void FillRange(ImVector& buffer, int n, T vmin, T vmax) { +template void FillRange(ImVector& buffer, int n, T vmin, T vmax) { buffer.resize(n); T step = (vmax - vmin) / (n - 1); for (int i = 0; i < n; ++i) { @@ -126,30 +121,49 @@ typedef void (*ImPlot3DLocator)(ImPlot3DTicker& ticker, const ImPlot3DRange& ran //----------------------------------------------------------------------------- struct ImDrawList3D { - ImVector IdxBuffer; // Index buffer - ImVector VtxBuffer; // Vertex buffer - ImVector ZBuffer; // Z buffer. Depth value for each triangle - unsigned int _VtxCurrentIdx; // [Internal] current vertex index - ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) - ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) - float* _ZWritePtr; // [Internal] point within ZBuffer.Data after each add command (to avoid using the ImVector<> operators too much) - ImDrawListFlags _Flags; // [Internal] draw list flags - ImDrawListSharedData* _SharedData; // [Internal] shared draw list data + // [Internal] Define which texture should be used when rendering triangles. + struct ImTextureBufferItem { + ImTextureRef TexRef; + unsigned int VtxIdx; + }; + + ImVector IdxBuffer; // Index buffer + ImVector VtxBuffer; // Vertex buffer + ImVector ZBuffer; // Z buffer. Depth value for each triangle + unsigned int _VtxCurrentIdx; // [Internal] current vertex index + ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + float* _ZWritePtr; // [Internal] point within ZBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImDrawListFlags _Flags; // [Internal] draw list flags + ImVector _TextureBuffer; // [Internal] buffer for SetTexture/ResetTexture + ImDrawListSharedData* _SharedData; // [Internal] shared draw list data ImDrawList3D() { - _VtxCurrentIdx = 0; - _VtxWritePtr = nullptr; - _IdxWritePtr = nullptr; - _ZWritePtr = nullptr; _Flags = ImDrawListFlags_None; _SharedData = nullptr; + ResetBuffers(); } void PrimReserve(int idx_count, int vtx_count); void PrimUnreserve(int idx_count, int vtx_count); + void SetTexture(ImTextureRef tex_ref); + void ResetTexture(); + void SortedMoveToImGuiDrawList(); + void ResetBuffers() { + IdxBuffer.clear(); + VtxBuffer.clear(); + ZBuffer.clear(); + _VtxCurrentIdx = 0; + _VtxWritePtr = VtxBuffer.Data; + _IdxWritePtr = IdxBuffer.Data; + _ZWritePtr = ZBuffer.Data; + _TextureBuffer.clear(); + ResetTexture(); + } + constexpr static unsigned int MaxIdx() { return sizeof(ImDrawIdx) == 2 ? 65535 : 4294967295; } }; @@ -345,9 +359,7 @@ struct ImPlot3DItemGroup { ImPlot3DLegend Legend; int ColormapIdx; - ImPlot3DItemGroup() { - ColormapIdx = 0; - } + ImPlot3DItemGroup() { ColormapIdx = 0; } int GetItemCount() const { return ItemPool.GetBufSize(); } ImGuiID GetItemID(const char* label_id) { return ImGui::GetID(label_id); } @@ -388,9 +400,7 @@ struct ImPlot3DTicker { ImVector Ticks; ImGuiTextBuffer TextBuffer; - ImPlot3DTicker() { - Reset(); - } + ImPlot3DTicker() { Reset(); } ImPlot3DTick& AddTick(double value, bool major, bool show_label, const char* label) { ImPlot3DTick tick(value, major, show_label); @@ -420,22 +430,16 @@ struct ImPlot3DTicker { return Ticks.back(); } - const char* GetText(int idx) const { - return TextBuffer.Buf.Data + Ticks[idx].TextOffset; - } + const char* GetText(int idx) const { return TextBuffer.Buf.Data + Ticks[idx].TextOffset; } - const char* GetText(const ImPlot3DTick& tick) const { - return GetText(tick.Idx); - } + const char* GetText(const ImPlot3DTick& tick) const { return GetText(tick.Idx); } void Reset() { Ticks.shrink(0); TextBuffer.Buf.shrink(0); } - int TickCount() const { - return Ticks.Size; - } + int TickCount() const { return Ticks.Size; } }; // Holds axis information @@ -454,6 +458,9 @@ struct ImPlot3DAxis { // Fit data bool FitThisFrame; ImPlot3DRange FitExtents; + // Constraints + ImPlot3DRange ConstraintRange; + ImPlot3DRange ConstraintZoom; // User input bool Hovered; bool Held; @@ -472,34 +479,54 @@ struct ImPlot3DAxis { ShowDefaultTicks = true; // Fit data FitThisFrame = true; - FitExtents.Min = HUGE_VAL; - FitExtents.Max = -HUGE_VAL; + FitExtents = ImPlot3DRange(HUGE_VAL, -HUGE_VAL); + // Constraints + ConstraintRange = ImPlot3DRange(-INFINITY, INFINITY); + ConstraintZoom = ImPlot3DRange(FLT_MIN, INFINITY); // User input Hovered = false; Held = false; } inline void Reset() { + RangeCond = ImPlot3DCond_None; + // Ticks + Ticker.Reset(); Formatter = nullptr; FormatterData = nullptr; Locator = nullptr; ShowDefaultTicks = true; - FitExtents.Min = HUGE_VAL; - FitExtents.Max = -HUGE_VAL; - Ticker.Reset(); + // Fit data + FitExtents = ImPlot3DRange(HUGE_VAL, -HUGE_VAL); + // Constraints + ConstraintRange = ImPlot3DRange(-INFINITY, INFINITY); + ConstraintZoom = ImPlot3DRange(FLT_MIN, INFINITY); } inline void SetRange(double v1, double v2) { Range.Min = (float)ImMin(v1, v2); Range.Max = (float)ImMax(v1, v2); + Constrain(); } inline bool SetMin(double _min, bool force = false) { if (!force && IsLockedMin()) return false; _min = ImPlot3D::ImConstrainNan((float)ImPlot3D::ImConstrainInf(_min)); + + // Constraints + if (_min < ConstraintRange.Min) + _min = ConstraintRange.Min; + double zoom = Range.Max - _min; + if (zoom < ConstraintZoom.Min) + _min = Range.Max - ConstraintZoom.Min; + if (zoom > ConstraintZoom.Max) + _min = Range.Max - ConstraintZoom.Max; + + // Ensure min is less than max if (_min >= Range.Max) return false; + Range.Min = (float)_min; return true; } @@ -508,12 +535,45 @@ struct ImPlot3DAxis { if (!force && IsLockedMax()) return false; _max = ImPlot3D::ImConstrainNan((float)ImPlot3D::ImConstrainInf(_max)); + + // Constraints + if (_max > ConstraintRange.Max) + _max = ConstraintRange.Max; + double zoom = _max - Range.Min; + if (zoom < ConstraintZoom.Min) + _max = Range.Min + ConstraintZoom.Min; + if (zoom > ConstraintZoom.Max) + _max = Range.Min + ConstraintZoom.Max; + + // Ensure max is greater than min if (_max <= Range.Min) return false; Range.Max = (float)_max; return true; } + inline void Constrain() { + Range.Min = (float)ImPlot3D::ImConstrainNan((float)ImPlot3D::ImConstrainInf((double)Range.Min)); + Range.Max = (float)ImPlot3D::ImConstrainNan((float)ImPlot3D::ImConstrainInf((double)Range.Max)); + if (Range.Min < ConstraintRange.Min) + Range.Min = ConstraintRange.Min; + if (Range.Max > ConstraintRange.Max) + Range.Max = ConstraintRange.Max; + float zoom = Range.Size(); + if (zoom < ConstraintZoom.Min) { + float delta = (ConstraintZoom.Min - zoom) * 0.5f; + Range.Min -= delta; + Range.Max += delta; + } + if (zoom > ConstraintZoom.Max) { + float delta = (zoom - ConstraintZoom.Max) * 0.5f; + Range.Min += delta; + Range.Max -= delta; + } + if (Range.Max <= Range.Min) + Range.Max = Range.Min + FLT_EPSILON; + } + inline bool IsRangeLocked() const { return RangeCond == ImPlot3DCond_Always; } inline bool IsLockedMin() const { return IsRangeLocked() || ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_LockMin); } inline bool IsLockedMax() const { return IsRangeLocked() || ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_LockMax); } @@ -522,6 +582,19 @@ struct ImPlot3DAxis { inline bool IsInputLockedMax() const { return IsLockedMax() || IsAutoFitting(); } inline bool IsInputLocked() const { return IsLocked() || IsAutoFitting(); } + inline bool IsPanLocked(bool increasing) { + if (ImPlot3D::ImHasFlag(Flags, ImPlot3DAxisFlags_PanStretch)) { + return IsInputLocked(); + } else { + if (IsLockedMin() || IsLockedMax() || IsAutoFitting()) + return false; + if (increasing) + return Range.Max == ConstraintRange.Max; + else + return Range.Min == ConstraintRange.Min; + } + } + inline void SetLabel(const char* label) { Label.Buf.shrink(0); if (label && ImGui::FindRenderedTextEnd(label, nullptr) != label) @@ -552,7 +625,9 @@ struct ImPlot3DPlot { ImRect CanvasRect; // Frame rectangle reduced by padding ImRect PlotRect; // Bounding rectangle for the actual plot area // Rotation & axes & box - ImPlot3DQuat Rotation; // Current rotation quaternion + ImPlot3DQuat InitialRotation; // Initial rotation quaternion + ImPlot3DQuat Rotation; // Current rotation quaternion + ImPlot3DCond RotationCond; ImPlot3DAxis Axes[3]; // X, Y, Z axes ImPlot3DPoint BoxScale; // Scale factor for plot box X, Y, Z axes // Animation @@ -568,7 +643,6 @@ struct ImPlot3DPlot { bool FitThisFrame; // Items ImPlot3DItemGroup Items; - ImPlot3DItem* CurrentItem; // 3D draw list ImDrawList3D DrawList; // Misc @@ -579,7 +653,9 @@ struct ImPlot3DPlot { PreviousFlags = Flags = ImPlot3DFlags_None; JustCreated = true; Initialized = false; + InitialRotation = ImPlot3DQuat(-0.513269f, -0.212596f, -0.318184f, 0.76819f); Rotation = ImPlot3DQuat(0.0f, 0.0f, 0.0f, 1.0f); + RotationCond = ImPlot3DCond_None; for (int i = 0; i < 3; i++) Axes[i] = ImPlot3DAxis(); BoxScale = ImPlot3DPoint(1.0f, 1.0f, 1.0f); @@ -590,7 +666,6 @@ struct ImPlot3DPlot { HeldEdgeIdx = -1; HeldPlaneIdx = -1; FitThisFrame = true; - CurrentItem = nullptr; ContextClick = false; OpenContextThisFrame = false; } @@ -602,6 +677,7 @@ struct ImPlot3DPlot { } inline bool HasTitle() const { return !Title.empty() && !ImPlot3D::ImHasFlag(Flags, ImPlot3DFlags_NoTitle); } inline const char* GetTitle() const { return Title.Buf.Data; } + inline bool IsRotationLocked() const { return RotationCond == ImPlot3DCond_Always; } void ExtendFit(const ImPlot3DPoint& point); ImPlot3DPoint RangeMin() const; @@ -615,6 +691,7 @@ struct ImPlot3DContext { ImPool Plots; ImPlot3DPlot* CurrentPlot; ImPlot3DItemGroup* CurrentItems; + ImPlot3DItem* CurrentItem; ImPlot3DNextItemData NextItemData; ImPlot3DStyle Style; ImVector ColorModifiers; @@ -649,6 +726,12 @@ IMPLOT3D_API bool IsColorAuto(ImPlot3DCol idx); IMPLOT3D_API ImVec4 GetAutoColor(ImPlot3DCol idx); IMPLOT3D_API const char* GetStyleColorName(ImPlot3DCol idx); +// Returns white or black text given background color +static inline ImU32 CalcTextColor(const ImVec4& bg) { + return (bg.x * 0.299f + bg.y * 0.587f + bg.z * 0.114f) > 0.5f ? IM_COL32_BLACK : IM_COL32_WHITE; +} +static inline ImU32 CalcTextColor(ImU32 bg) { return CalcTextColor(ImGui::ColorConvertU32ToFloat4(bg)); } + // Get styling data for next item (call between BeginItem/EndItem) IMPLOT3D_API const ImPlot3DNextItemData& GetItemData(); @@ -658,6 +741,10 @@ IMPLOT3D_API ImU32 GetColormapColorU32(int idx, ImPlot3DColormap cmap); // Returns the next unused colormap color and advances the colormap. Can be used to skip colors if desired IMPLOT3D_API ImU32 NextColormapColorU32(); +// Render a colormap bar +IMPLOT3D_API void RenderColorBar(const ImU32* colors, int size, ImDrawList& DrawList, const ImRect& bounds, bool vert, bool reversed, + bool continuous); + //----------------------------------------------------------------------------- // [SECTION] Item Utils //----------------------------------------------------------------------------- @@ -668,6 +755,9 @@ IMPLOT3D_API void EndItem(); // Register or get an existing item from the current plot IMPLOT3D_API ImPlot3DItem* RegisterOrGetItem(const char* label_id, ImPlot3DItemFlags flags, bool* just_created = nullptr); +// Gets the current item from ImPlot3DContext +IMPLOT3D_API ImPlot3DItem* GetCurrentItem(); + // Busts the cache for every item for every plot in the current context IMPLOT3D_API void BustItemCache(); @@ -678,7 +768,7 @@ IMPLOT3D_API void AddTextRotated(ImDrawList* draw_list, ImVec2 pos, float angle, // [SECTION] Plot Utils //----------------------------------------------------------------------------- -// Gets the current plot from the current ImPlot3DContext +// Gets the current plot from ImPlot3DContext IMPLOT3D_API ImPlot3DPlot* GetCurrentPlot(); // Busts the cache for every plot in the current context diff --git a/lib/third_party/imgui/implot3d/source/implot3d.cpp b/lib/third_party/imgui/implot3d/source/implot3d.cpp index aae78de05..e0f21103c 100644 --- a/lib/third_party/imgui/implot3d/source/implot3d.cpp +++ b/lib/third_party/imgui/implot3d/source/implot3d.cpp @@ -1,5 +1,5 @@ //-------------------------------------------------- -// ImPlot3D v0.1 +// ImPlot3D v0.3 WIP // implot3d.cpp // Date: 2024-11-16 // Author: Breno Cunha Queiroz (brenocq.com) @@ -39,6 +39,7 @@ // [SECTION] ImPlot3DAxis // [SECTION] ImPlot3DPlot // [SECTION] ImPlot3DStyle +// [SECTION] Metrics //----------------------------------------------------------------------------- // [SECTION] Includes @@ -62,7 +63,8 @@ // [SECTION] Macros //----------------------------------------------------------------------------- -#define IMPLOT3D_CHECK_CTX() IM_ASSERT_USER_ERROR(GImPlot3D != nullptr, "No current context. Did you call ImPlot3D::CreateContext() or ImPlot3D::SetCurrentContext()?") +#define IMPLOT3D_CHECK_CTX() \ + IM_ASSERT_USER_ERROR(GImPlot3D != nullptr, "No current context. Did you call ImPlot3D::CreateContext() or ImPlot3D::SetCurrentContext()?") #define IMPLOT3D_CHECK_PLOT() IM_ASSERT_USER_ERROR(GImPlot3D->CurrentPlot != nullptr, "No active plot. Did you call ImPlot3D::BeginPlot()?") //----------------------------------------------------------------------------- @@ -76,8 +78,6 @@ namespace ImPlot3D { ImPlot3DContext* GImPlot3D = nullptr; #endif -static ImPlot3DQuat init_rotation = ImPlot3DQuat(-0.513269f, -0.212596f, -0.318184f, 0.76819f); - ImPlot3DContext* CreateContext() { ImPlot3DContext* ctx = IM_NEW(ImPlot3DContext)(); if (GImPlot3D == nullptr) @@ -109,11 +109,16 @@ void AddTextRotated(ImDrawList* draw_list, ImVec2 pos, float angle, ImU32 col, c ImGuiContext& g = *GImGui; ImFont* font = g.Font; +#ifdef IMGUI_HAS_TEXTURES + ImFontBaked* fontBaked = g.Font->GetFontBaked(g.FontSize); + const float scale = g.FontSize / fontBaked->Size; +#else + const float scale = g.FontSize / font->FontSize; +#endif + // Align to be pixel perfect pos = ImFloor(pos); - const float scale = g.FontSize / font->FontSize; - // Measure the size of the text in unrotated coordinates ImVec2 text_size = font->CalcTextSizeA(g.FontSize, FLT_MAX, 0.0f, text_begin, text_end, nullptr); @@ -141,7 +146,11 @@ void AddTextRotated(ImDrawList* draw_list, ImVec2 pos, float angle, ImU32 col, c break; } +#ifdef IMGUI_HAS_TEXTURES + const ImFontGlyph* glyph = fontBaked->FindGlyph((ImWchar)c); +#else const ImFontGlyph* glyph = font->FindGlyph((ImWchar)c); +#endif if (glyph == nullptr) { continue; } @@ -170,9 +179,7 @@ void AddTextRotated(ImDrawList* draw_list, ImVec2 pos, float angle, ImU32 col, c ImVec2 uv1 = ImVec2(glyph->U1, glyph->V1); // Render the glyph quad - draw_list->PrimQuadUV(corners[0], corners[1], corners[2], corners[3], - uv0, ImVec2(glyph->U1, glyph->V0), - uv1, ImVec2(glyph->U0, glyph->V1), + draw_list->PrimQuadUV(corners[0], corners[1], corners[2], corners[3], uv0, ImVec2(glyph->U1, glyph->V0), uv1, ImVec2(glyph->U0, glyph->V1), col); // Advance the pen position @@ -196,6 +203,30 @@ void AddTextCentered(ImDrawList* draw_list, ImVec2 top_center, ImU32 col, const // [SECTION] Legend Utils //----------------------------------------------------------------------------- +static const char* short_legend_location[9] = {"C", "N", "S", "W", "E", "NW", "NE", "SW", "SE"}; + +static const char* GetShortLegendLocationName(ImPlot3DLocation loc) { + if (loc == ImPlot3DLocation_Center) + return short_legend_location[0]; + if (loc == ImPlot3DLocation_North) + return short_legend_location[1]; + if (loc == ImPlot3DLocation_South) + return short_legend_location[2]; + if (loc == ImPlot3DLocation_West) + return short_legend_location[3]; + if (loc == ImPlot3DLocation_East) + return short_legend_location[4]; + if (loc == ImPlot3DLocation_NorthWest) + return short_legend_location[5]; + if (loc == ImPlot3DLocation_NorthEast) + return short_legend_location[6]; + if (loc == ImPlot3DLocation_SouthWest) + return short_legend_location[7]; + if (loc == ImPlot3DLocation_SouthEast) + return short_legend_location[8]; + return nullptr; +} + ImVec2 GetLocationPos(const ImRect& outer_rect, const ImVec2& inner_size, ImPlot3DLocation loc, const ImVec2& pad) { ImVec2 pos; // Legend x coordinate @@ -231,11 +262,13 @@ ImVec2 CalcLegendSize(ImPlot3DItemGroup& items, const ImVec2& pad, const ImVec2& sum_label_width += label_width; } // Compute legend size - const ImVec2 legend_size = vertical ? ImVec2(pad.x * 2 + icon_size + max_label_width, pad.y * 2 + nItems * txt_ht + (nItems - 1) * spacing.y) : ImVec2(pad.x * 2 + icon_size * nItems + sum_label_width + (nItems - 1) * spacing.x, pad.y * 2 + txt_ht); + const ImVec2 legend_size = vertical ? ImVec2(pad.x * 2 + icon_size + max_label_width, pad.y * 2 + nItems * txt_ht + (nItems - 1) * spacing.y) + : ImVec2(pad.x * 2 + icon_size * nItems + sum_label_width + (nItems - 1) * spacing.x, pad.y * 2 + txt_ht); return legend_size; } -void ShowLegendEntries(ImPlot3DItemGroup& items, const ImRect& legend_bb, bool hovered, const ImVec2& pad, const ImVec2& spacing, bool vertical, ImDrawList& draw_list) { +void ShowLegendEntries(ImPlot3DItemGroup& items, const ImRect& legend_bb, bool hovered, const ImVec2& pad, const ImVec2& spacing, bool vertical, + ImDrawList& draw_list) { const float txt_ht = ImGui::GetTextLineHeight(); const float icon_size = txt_ht; const float icon_shrink = 2; @@ -253,7 +286,8 @@ void ShowLegendEntries(ImPlot3DItemGroup& items, const ImRect& legend_bb, bool h ImPlot3DItem* item = items.GetLegendItem(idx); const char* label = items.GetLegendLabel(idx); const float label_width = ImGui::CalcTextSize(label, nullptr, true).x; - const ImVec2 top_left = vertical ? legend_bb.Min + pad + ImVec2(0, i * (txt_ht + spacing.y)) : legend_bb.Min + pad + ImVec2(i * (icon_size + spacing.x) + sum_label_width, 0); + const ImVec2 top_left = vertical ? legend_bb.Min + pad + ImVec2(0, i * (txt_ht + spacing.y)) + : legend_bb.Min + pad + ImVec2(i * (icon_size + spacing.x) + sum_label_width, 0); sum_label_width += label_width; ImRect icon_bb; icon_bb.Min = top_left + ImVec2(icon_shrink, icon_shrink); @@ -315,10 +349,7 @@ void RenderLegend() { ImPlot3DLegend& legend = plot.Items.Legend; const bool legend_horz = ImPlot3D::ImHasFlag(legend.Flags, ImPlot3DLegendFlags_Horizontal); const ImVec2 legend_size = CalcLegendSize(plot.Items, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !legend_horz); - const ImVec2 legend_pos = GetLocationPos(plot.PlotRect, - legend_size, - legend.Location, - gp.Style.LegendPadding); + const ImVec2 legend_pos = GetLocationPos(plot.PlotRect, legend_size, legend.Location, gp.Style.LegendPadding); legend.Rect = ImRect(legend_pos, legend_pos + legend_size); // Test hover @@ -435,6 +466,31 @@ static const int axis_corners_lookup_3d[8][3][2] = { {{4, 5}, {4, 7}, {3, 7}}, }; +// Lookup table for axis_edges based on active_faces (3D plot) +static const int axis_edges_lookup_3d[8][3] = { + // Index 0: active_faces = {0, 0, 0} + {2, 1, 9}, + // Index 1: active_faces = {0, 0, 1} + {6, 5, 9}, + // Index 2: active_faces = {0, 1, 0} + {0, 1, 10}, + // Index 3: active_faces = {0, 1, 1} + {4, 5, 10}, + // Index 4: active_faces = {1, 0, 0} + {2, 3, 8}, + // Index 5: active_faces = {1, 0, 1} + {6, 7, 8}, + // Index 6: active_faces = {1, 1, 0} + {0, 3, 11}, + // Index 7: active_faces = {1, 1, 1} + {4, 7, 11}, +}; + +// Convert the X, Y and Z active_faces array to a integer value representation that can be looked up in axis_corners_lookup_3d +int Active3DFacesToAxisLookupIndex(const bool* active_faces) { + return ((int)active_faces[0] << 2) | ((int)active_faces[1] << 1) | ((int)active_faces[2]); +} + int GetMouseOverPlane(const ImPlot3DPlot& plot, const bool* active_faces, const ImVec2* corners_pix, int* plane_out = nullptr) { ImGuiIO& io = ImGui::GetIO(); ImVec2 mouse_pos = io.MousePos; @@ -639,7 +695,8 @@ void RenderGrid(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DP } } -void RenderTickMarks(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint* corners, const ImVec2* corners_pix, const int axis_corners[3][2], const int plane_2d) { +void RenderTickMarks(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint* corners, const ImVec2* corners_pix, + const int axis_corners[3][2], const int plane_2d) { ImU32 col_tick = GetStyleColorU32(ImPlot3DCol_AxisTick); auto DeterminePlaneForAxis = [&](int axis_idx) { @@ -745,7 +802,8 @@ void RenderTickMarks(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPl } } -void RenderTickLabels(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint* corners, const ImVec2* corners_pix, const int axis_corners[3][2]) { +void RenderTickLabels(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint* corners, const ImVec2* corners_pix, + const int axis_corners[3][2]) { ImU32 col_tick_txt = GetStyleColorU32(ImPlot3DCol_AxisText); for (int a = 0; a < 3; a++) { @@ -839,7 +897,8 @@ void RenderTickLabels(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImP } } -void RenderAxisLabels(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint* corners, const ImVec2* corners_pix, const int axis_corners[3][2]) { +void RenderAxisLabels(ImDrawList* draw_list, const ImPlot3DPlot& plot, const ImPlot3DPoint* corners, const ImVec2* corners_pix, + const int axis_corners[3][2]) { for (int a = 0; a < 3; a++) { const ImPlot3DAxis& axis = plot.Axes[a]; if (!axis.HasLabel()) @@ -893,7 +952,7 @@ void ComputeActiveFaces(bool* active_faces, const ImPlot3DQuat& rotation, const }; int num_deg = 0; // Check number of planes that are degenerate (seen as a line) - for (int i = 0; i < 3; ++i) { + for (int i = 0; i < 3; i++) { // Determine the active face based on the Z component if (fabs(rot_face_n[i].z) < 0.025) { // If aligned with the plane, choose the min face for bottom/left @@ -925,35 +984,59 @@ void ComputeBoxCorners(ImPlot3DPoint* corners, const ImPlot3DPoint& range_min, c corners[7] = ImPlot3DPoint(range_min.x, range_max.y, range_max.z); // 7 } +// Convert a position in the plot's NDC to pixels +ImVec2 NDCToPixels(const ImPlot3DPlot& plot, const ImPlot3DPoint& point) { + ImVec2 center = plot.PlotRect.GetCenter(); + ImPlot3DPoint point_pix = plot.GetBoxZoom() * (plot.Rotation * point); + point_pix.y *= -1.0f; // Invert y-axis + point_pix.x += center.x; + point_pix.y += center.y; + + return {point_pix.x, point_pix.y}; +} + +// Convert a position in the plot's coordinate system to the plot's normalized device coordinate system (NDC) +ImPlot3DPoint PlotToNDC(const ImPlot3DPlot& plot, const ImPlot3DPoint& point) { + ImPlot3DPoint ndc_point; + for (int i = 0; i < 3; i++) { + const ImPlot3DAxis& axis = plot.Axes[i]; + float ndc_range = 0.5f * plot.BoxScale[i]; + float t = (point[i] - axis.Range.Min) / (axis.Range.Max - axis.Range.Min); + t *= plot.BoxScale[i]; + ndc_point[i] = ImPlot3D::ImHasFlag(axis.Flags, ImPlot3DAxisFlags_Invert) ? (ndc_range - t) : (t - ndc_range); + } + return ndc_point; +} + +// Convert a position in the plot's coordinate system to pixels +ImVec2 PlotToPixels(const ImPlot3DPlot& plot, const ImPlot3DPoint& point) { return NDCToPixels(plot, PlotToNDC(plot, point)); } + // Function to compute the box corners in pixel space -void ComputeBoxCornersPix(ImVec2* corners_pix, const ImPlot3DPoint* corners) { +void ComputeBoxCornersPix(const ImPlot3DPlot& plot, ImVec2* corners_pix, const ImPlot3DPoint* corners) { for (int i = 0; i < 8; i++) { - corners_pix[i] = PlotToPixels(corners[i]); + corners_pix[i] = PlotToPixels(plot, corners[i]); } } -void RenderPlotBox(ImDrawList* draw_list, const ImPlot3DPlot& plot) { +// Function to get axes parameters which can then be used later down the line +void GetAxesParameters(const ImPlot3DPlot& plot, bool* active_faces, ImVec2* corners_pix, ImPlot3DPoint* corners, int& plane_2d, + int axis_corners[3][2]) { // Get plot parameters const ImPlot3DQuat& rotation = plot.Rotation; ImPlot3DPoint range_min = plot.RangeMin(); ImPlot3DPoint range_max = plot.RangeMax(); // Compute active faces - bool active_faces[3]; - int plane_2d = -1; ComputeActiveFaces(active_faces, rotation, plot.Axes, &plane_2d); bool is_2d = plane_2d != -1; // Compute box corners in plot space - ImPlot3DPoint corners[8]; ComputeBoxCorners(corners, range_min, range_max); // Compute box corners in pixel space - ImVec2 corners_pix[8]; - ComputeBoxCornersPix(corners_pix, corners); + ComputeBoxCornersPix(plot, corners_pix, corners); // Compute axes start and end corners (given current rotation) - int axis_corners[3][2]; if (is_2d) { int face = plane_2d + 3 * active_faces[plane_2d]; // Face of the 2D plot int common_edges[2] = {-1, -1}; // Edges shared by the 3 faces @@ -1028,12 +1111,22 @@ void RenderPlotBox(ImDrawList* draw_list, const ImPlot3DPlot& plot) { axis_corners[y_axis][1] = y_corner; } } else { - int index = ((int)active_faces[0] << 2) | ((int)active_faces[1] << 1) | ((int)active_faces[2]); + int index = Active3DFacesToAxisLookupIndex(active_faces); for (int a = 0; a < 3; a++) { axis_corners[a][0] = axis_corners_lookup_3d[index][a][0]; axis_corners[a][1] = axis_corners_lookup_3d[index][a][1]; } } +} + +void RenderPlotBox(ImDrawList* draw_list, const ImPlot3DPlot& plot) { + bool active_faces[3]; + ImVec2 corners_pix[8]; + ImPlot3DPoint corners[8]; + int plane_2d; + int axis_corners[3][2]; + + GetAxesParameters(plot, active_faces, corners_pix, corners, plane_2d, axis_corners); // Render components RenderPlotBackground(draw_list, plot, corners_pix, active_faces, plane_2d); @@ -1106,7 +1199,7 @@ void Locator_Default(ImPlot3DTicker& ticker, const ImPlot3DRange& range, float p } ticker.AddTick(major, true, true, formatter, formatter_data); } - for (int i = 1; i < nMinor; ++i) { + for (int i = 1; i < nMinor; i++) { double minor = major + i * interval / nMinor; if (range.Contains((float)minor)) { ticker.AddTick(minor, false, true, formatter, formatter_data); @@ -1124,7 +1217,7 @@ void Locator_Default(ImPlot3DTicker& ticker, const ImPlot3DRange& range, float p } void AddTicksCustom(const double* values, const char* const labels[], int n, ImPlot3DTicker& ticker, ImPlot3DFormatter formatter, void* data) { - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; i++) { if (labels != nullptr) ticker.AddTick(values[i], false, true, labels[i]); else @@ -1153,15 +1246,15 @@ bool ShowLegendContextMenu(ImPlot3DLegend& legend, bool visible) { legend.Flags &= ~ImPlot3DLegendFlags_Horizontal; ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 2)); // clang-format off - if (ImGui::Button("NW",ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_NorthWest; } ImGui::SameLine(); - if (ImGui::Button("N", ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_North; } ImGui::SameLine(); - if (ImGui::Button("NE",ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_NorthEast; } - if (ImGui::Button("W", ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_West; } ImGui::SameLine(); - if (ImGui::InvisibleButton("C", ImVec2(1.5f*s,s))) { } ImGui::SameLine(); - if (ImGui::Button("E", ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_East; } - if (ImGui::Button("SW",ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_SouthWest; } ImGui::SameLine(); - if (ImGui::Button("S", ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_South; } ImGui::SameLine(); - if (ImGui::Button("SE",ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_SouthEast; } + if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_NorthWest),ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_NorthWest; } ImGui::SameLine(); + if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_North) , ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_North; } ImGui::SameLine(); + if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_NorthEast), ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_NorthEast; } + if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_West), ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_West; } ImGui::SameLine(); + if (ImGui::InvisibleButton(GetShortLegendLocationName(ImPlot3DLocation_Center), ImVec2(1.5f*s,s))) { } ImGui::SameLine(); + if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_East), ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_East; } + if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_SouthWest),ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_SouthWest; } ImGui::SameLine(); + if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_South), ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_South; } ImGui::SameLine(); + if (ImGui::Button(GetShortLegendLocationName(ImPlot3DLocation_SouthEast),ImVec2(1.5f*s,s))) { legend.Location = ImPlot3DLocation_SouthEast; } // clang-format on ImGui::PopStyleVar(); return ret; @@ -1174,7 +1267,8 @@ void ShowAxisContextMenu(ImPlot3DAxis& axis) { bool grid = axis.HasGridLines(); bool ticks = axis.HasTickMarks(); bool labels = axis.HasTickLabels(); - double drag_speed = (axis.Range.Size() <= FLT_EPSILON) ? FLT_EPSILON * 1.0e+13 : 0.01 * axis.Range.Size(); // recover from almost equal axis limits. + double drag_speed = + (axis.Range.Size() <= FLT_EPSILON) ? FLT_EPSILON * 1.0e+13 : 0.01 * axis.Range.Size(); // recover from almost equal axis limits. ImGui::BeginDisabled(always_locked); ImGui::CheckboxFlags("##LockMin", (unsigned int*)&axis.Flags, ImPlot3DAxisFlags_LockMin); @@ -1315,7 +1409,7 @@ bool BeginPlot(const char* title_id, const ImVec2& size, ImPlot3DFlags flags) { plot.ID = ID; plot.JustCreated = just_created; if (just_created) { - plot.Rotation = init_rotation; + plot.Rotation = plot.InitialRotation; plot.FitThisFrame = true; for (int i = 0; i < 3; i++) { plot.Axes[i] = ImPlot3DAxis(); @@ -1327,6 +1421,7 @@ bool BeginPlot(const char* title_id, const ImVec2& size, ImPlot3DFlags flags) { plot.PreviousFlags = flags; plot.SetupLocked = false; plot.OpenContextThisFrame = false; + plot.RotationCond = ImPlot3DCond_None; // Populate title plot.SetTitle(title_id); @@ -1338,17 +1433,13 @@ bool BeginPlot(const char* title_id, const ImVec2& size, ImPlot3DFlags flags) { if (frame_size.y < gp.Style.PlotMinSize.y && size.y < 0.0f) frame_size.y = gp.Style.PlotMinSize.y; - // Create child window to capture scroll - ImGui::BeginChild(title_id, frame_size, false, ImGuiWindowFlags_NoScrollbar); - window = ImGui::GetCurrentWindow(); - window->ScrollMax.y = 1.0f; - + // Create plot ImGui item plot.FrameRect = ImRect(window->DC.CursorPos, window->DC.CursorPos + frame_size); ImGui::ItemSize(plot.FrameRect); if (!ImGui::ItemAdd(plot.FrameRect, plot.ID, &plot.FrameRect)) { gp.CurrentPlot = nullptr; gp.CurrentItems = nullptr; - ImGui::EndChild(); + gp.CurrentItem = nullptr; return false; } @@ -1356,9 +1447,8 @@ bool BeginPlot(const char* title_id, const ImVec2& size, ImPlot3DFlags flags) { plot.Items.Legend.Reset(); // Reset axes - for (int i = 0; i < ImAxis3D_COUNT; ++i) { + for (int i = 0; i < ImAxis3D_COUNT; i++) plot.Axes[i].Reset(); - } // Push frame rect clipping ImGui::PushClipRect(plot.FrameRect.Min, plot.FrameRect.Max, true); @@ -1439,12 +1529,10 @@ void EndPlot() { // Pop frame rect clipping ImGui::PopClipRect(); - // End child window - ImGui::EndChild(); - // Reset current plot gp.CurrentPlot = nullptr; gp.CurrentItems = nullptr; + gp.CurrentItem = nullptr; // Reset the plot items for the next frame for (int i = 0; i < plot.Items.GetItemCount(); i++) @@ -1455,6 +1543,17 @@ void EndPlot() { // [SECTION] Setup //----------------------------------------------------------------------------- +static const float ANIMATION_ANGULAR_VELOCITY = 2 * 3.1415f; + +float CalcAnimationTime(ImPlot3DQuat q0, ImPlot3DQuat q1) { + // Compute the angular distance between orientations + float dot_product = ImClamp(q0.Dot(q1), -1.0f, 1.0f); + float angle = 2.0f * acosf(fabsf(dot_product)); + + // Calculate animation time for constant the angular velocity + return angle / ANIMATION_ANGULAR_VELOCITY; +} + void SetupAxis(ImAxis3D idx, const char* label, ImPlot3DAxisFlags flags) { ImPlot3DContext& gp = *GImPlot3D; IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, @@ -1472,7 +1571,7 @@ void SetupAxis(ImAxis3D idx, const char* label, ImPlot3DAxisFlags flags) { void SetupAxisLimits(ImAxis3D idx, double min_lim, double max_lim, ImPlot3DCond cond) { ImPlot3DContext& gp = *GImPlot3D; IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, - "SetupAxisLimits() needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); // get plot and axis + "SetupAxisLimits() needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); ImPlot3DPlot& plot = *gp.CurrentPlot; ImPlot3DAxis& axis = plot.Axes[idx]; if (!plot.Initialized || cond == ImPlot3DCond_Always) { @@ -1499,11 +1598,7 @@ void SetupAxisTicks(ImAxis3D idx, const double* values, int n_ticks, const char* ImPlot3DPlot& plot = *gp.CurrentPlot; ImPlot3DAxis& axis = plot.Axes[idx]; axis.ShowDefaultTicks = keep_default; - AddTicksCustom(values, - labels, - n_ticks, - axis.Ticker, - axis.Formatter ? axis.Formatter : Formatter_Default, + AddTicksCustom(values, labels, n_ticks, axis.Ticker, axis.Formatter ? axis.Formatter : Formatter_Default, (axis.Formatter && axis.FormatterData) ? axis.FormatterData : (void*)IMPLOT3D_LABEL_FORMAT); } @@ -1517,7 +1612,28 @@ void SetupAxisTicks(ImAxis3D idx, double v_min, double v_max, int n_ticks, const SetupAxisTicks(idx, temp.Data, n_ticks, labels, keep_default); } -void SetupAxes(const char* x_label, const char* y_label, const char* z_label, ImPlot3DAxisFlags x_flags, ImPlot3DAxisFlags y_flags, ImPlot3DAxisFlags z_flags) { +void SetupAxisLimitsConstraints(ImAxis3D idx, double v_min, double v_max) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + ImPlot3DAxis& axis = plot.Axes[idx]; + axis.ConstraintRange.Min = (float)v_min; + axis.ConstraintRange.Max = (float)v_max; +} + +void SetupAxisZoomConstraints(ImAxis3D idx, double z_min, double z_max) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + ImPlot3DAxis& axis = plot.Axes[idx]; + axis.ConstraintZoom.Min = (float)z_min; + axis.ConstraintZoom.Max = (float)z_max; +} + +void SetupAxes(const char* x_label, const char* y_label, const char* z_label, ImPlot3DAxisFlags x_flags, ImPlot3DAxisFlags y_flags, + ImPlot3DAxisFlags z_flags) { SetupAxis(ImAxis3D_X, x_label, x_flags); SetupAxis(ImAxis3D_Y, y_label, y_flags); SetupAxis(ImAxis3D_Z, z_label, z_flags); @@ -1531,6 +1647,51 @@ void SetupAxesLimits(double x_min, double x_max, double y_min, double y_max, dou GImPlot3D->CurrentPlot->FitThisFrame = false; } +void SetupBoxRotation(float elevation, float azimuth, bool animate, ImPlot3DCond cond) { + // Convert angles from degrees to radians + float elev_rad = elevation * IM_PI / 180.0f; + float azim_rad = azimuth * IM_PI / 180.0f; + + // Call quaternion SetupBoxRotation + SetupBoxRotation(ImPlot3DQuat::FromElAz(elev_rad, azim_rad), animate, cond); +} + +void SetupBoxRotation(ImPlot3DQuat rotation, bool animate, ImPlot3DCond cond) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "SetupBoxRotation() needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + + if (!plot.Initialized || cond == ImPlot3DCond_Always) { + if (!animate) { + plot.Rotation = rotation; + plot.AnimationTime = 0.0f; // Force any running rotation animation to stop + } else { + plot.RotationAnimationEnd = rotation; + plot.AnimationTime = CalcAnimationTime(plot.Rotation, plot.RotationAnimationEnd); + } + plot.RotationCond = cond; + } +} + +void SetupBoxInitialRotation(float elevation, float azimuth) { + // Convert angles from degrees to radians + float elev_rad = elevation * IM_PI / 180.0f; + float azim_rad = azimuth * IM_PI / 180.0f; + + // Call quaternion SetupBoxInitialRotation + SetupBoxInitialRotation(ImPlot3DQuat::FromElAz(elev_rad, azim_rad)); +} + +void SetupBoxInitialRotation(ImPlot3DQuat rotation) { + ImPlot3DContext& gp = *GImPlot3D; + IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, + "SetupBoxInitialRotation() needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!"); + ImPlot3DPlot& plot = *gp.CurrentPlot; + + plot.InitialRotation = rotation; +} + void SetupBoxScale(float x, float y, float z) { ImPlot3DContext& gp = *GImPlot3D; IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, @@ -1544,8 +1705,7 @@ void SetupLegend(ImPlot3DLocation location, ImPlot3DLegendFlags flags) { ImPlot3DContext& gp = *GImPlot3D; IM_ASSERT_USER_ERROR(gp.CurrentPlot != nullptr && !gp.CurrentPlot->SetupLocked, "SetupLegend() needs to be called after BeginPlot() and before any setup locking functions (e.g. PlotX)!"); - IM_ASSERT_USER_ERROR(gp.CurrentItems != nullptr, - "SetupLegend() needs to be called within an itemized context!"); + IM_ASSERT_USER_ERROR(gp.CurrentItems != nullptr, "SetupLegend() needs to be called within an itemized context!"); ImPlot3DLegend& legend = gp.CurrentItems->Legend; if (legend.PreviousLocation != location) legend.Location = location; @@ -1559,9 +1719,7 @@ void SetupLegend(ImPlot3DLocation location, ImPlot3DLegendFlags flags) { // [SECTION] Plot Utils //----------------------------------------------------------------------------- -ImPlot3DPlot* GetCurrentPlot() { - return GImPlot3D->CurrentPlot; -} +ImPlot3DPlot* GetCurrentPlot() { return GImPlot3D->CurrentPlot; } void BustPlotCache() { ImPlot3DContext& gp = *GImPlot3D; @@ -1574,9 +1732,7 @@ ImVec2 PlotToPixels(const ImPlot3DPoint& point) { return NDCToPixels(PlotToNDC(point)); } -ImVec2 PlotToPixels(double x, double y, double z) { - return PlotToPixels(ImPlot3DPoint((float)x, (float)y, (float)z)); -} +ImVec2 PlotToPixels(double x, double y, double z) { return PlotToPixels(ImPlot3DPoint((float)x, (float)y, (float)z)); } ImPlot3DRay PixelsToPlotRay(const ImVec2& pix) { ImPlot3DContext& gp = *GImPlot3D; @@ -1584,9 +1740,7 @@ ImPlot3DRay PixelsToPlotRay(const ImVec2& pix) { return NDCRayToPlotRay(PixelsToNDCRay(pix)); } -ImPlot3DRay PixelsToPlotRay(double x, double y) { - return PixelsToPlotRay(ImVec2((float)x, (float)y)); -} +ImPlot3DRay PixelsToPlotRay(double x, double y) { return PixelsToPlotRay(ImVec2((float)x, (float)y)); } ImPlot3DPoint PixelsToPlotPlane(const ImVec2& pix, ImPlane3D plane, bool mask) { ImPlot3DContext& gp = *GImPlot3D; @@ -1638,8 +1792,7 @@ ImPlot3DPoint PixelsToPlotPlane(const ImVec2& pix, ImPlane3D plane, bool mask) { // Helper lambda to check if point P is within the plot box auto InRange = [&](const ImPlot3DPoint& P) { - return P.x >= -0.5f * plot.BoxScale.x && P.x <= 0.5f * plot.BoxScale.x && - P.y >= -0.5f * plot.BoxScale.y && P.y <= 0.5f * plot.BoxScale.y && + return P.x >= -0.5f * plot.BoxScale.x && P.x <= 0.5f * plot.BoxScale.x && P.y >= -0.5f * plot.BoxScale.y && P.y <= 0.5f * plot.BoxScale.y && P.z >= -0.5f * plot.BoxScale.z && P.z <= 0.5f * plot.BoxScale.z; }; @@ -1664,9 +1817,7 @@ ImPlot3DPoint PixelsToPlotPlane(const ImVec2& pix, ImPlane3D plane, bool mask) { return NDCToPlot(P); } -ImPlot3DPoint PixelsToPlotPlane(double x, double y, ImPlane3D plane, bool mask) { - return PixelsToPlotPlane(ImVec2((float)x, (float)y), plane, mask); -} +ImPlot3DPoint PixelsToPlotPlane(double x, double y, ImPlane3D plane, bool mask) { return PixelsToPlotPlane(ImVec2((float)x, (float)y), plane, mask); } ImVec2 GetPlotPos() { ImPlot3DContext& gp = *GImPlot3D; @@ -1700,15 +1851,7 @@ ImPlot3DPoint PlotToNDC(const ImPlot3DPoint& point) { ImPlot3DPlot& plot = *gp.CurrentPlot; SetupLock(); - ImPlot3DPoint ndc_point; - for (int i = 0; i < 3; i++) { - ImPlot3DAxis& axis = plot.Axes[i]; - float ndc_range = 0.5f * plot.BoxScale[i]; - float t = (point[i] - axis.Range.Min) / (axis.Range.Max - axis.Range.Min); - t *= plot.BoxScale[i]; - ndc_point[i] = ImPlot3D::ImHasFlag(axis.Flags, ImPlot3DAxisFlags_Invert) ? (ndc_range - t) : (t - ndc_range); - } - return ndc_point; + return PlotToNDC(plot, point); } ImPlot3DPoint NDCToPlot(const ImPlot3DPoint& point) { @@ -1734,13 +1877,7 @@ ImVec2 NDCToPixels(const ImPlot3DPoint& point) { ImPlot3DPlot& plot = *gp.CurrentPlot; SetupLock(); - ImVec2 center = plot.PlotRect.GetCenter(); - ImPlot3DPoint point_pix = plot.GetBoxZoom() * (plot.Rotation * point); - point_pix.y *= -1.0f; // Invert y-axis - point_pix.x += center.x; - point_pix.y += center.y; - - return {point_pix.x, point_pix.y}; + return NDCToPixels(plot, point); } ImPlot3DRay PixelsToNDCRay(const ImVec2& pix) { @@ -1795,7 +1932,6 @@ ImPlot3DRay NDCRayToPlotRay(const ImPlot3DRay& ray) { //----------------------------------------------------------------------------- static const float MOUSE_CURSOR_DRAG_THRESHOLD = 5.0f; -static const float ANIMATION_ANGULAR_VELOCITY = 2 * 3.1415f; void HandleInput(ImPlot3DPlot& plot) { ImGuiIO& IO = ImGui::GetIO(); @@ -1827,7 +1963,7 @@ void HandleInput(ImPlot3DPlot& plot) { ImPlot3DPoint corners[8]; ComputeBoxCorners(corners, range_min, range_max); ImVec2 corners_pix[8]; - ComputeBoxCornersPix(corners_pix, corners); + ComputeBoxCornersPix(plot, corners_pix, corners); int hovered_plane_idx = -1; int hovered_plane = GetMouseOverPlane(plot, active_faces, corners_pix, &hovered_plane_idx); int hovered_edge_idx = -1; @@ -1917,7 +2053,8 @@ void HandleInput(ImPlot3DPlot& plot) { // Adjust plot range to translate the plot for (int i = 0; i < 3; i++) { if (plot.Axes[i].Hovered) { - if (!plot.Axes[i].IsInputLocked()) { + bool increasing = delta_plot[i] < 0.0f; + if (delta_plot[i] != 0.0f && !plot.Axes[i].IsPanLocked(increasing)) { plot.Axes[i].SetMin(plot.Axes[i].Range.Min - delta_plot[i]); plot.Axes[i].SetMax(plot.Axes[i].Range.Max - delta_plot[i]); } @@ -1941,7 +2078,8 @@ void HandleInput(ImPlot3DPlot& plot) { // Apply translation to the selected axes for (int i = 0; i < 3; i++) { if (plot.Axes[i].Hovered) { - if (!plot.Axes[i].IsInputLocked()) { + bool increasing = delta_plot[i] < 0.0f; + if (delta_plot[i] != 0.0f && !plot.Axes[i].IsPanLocked(increasing)) { plot.Axes[i].SetMin(plot.Axes[i].Range.Min - delta_plot[i]); plot.Axes[i].SetMax(plot.Axes[i].Range.Max - delta_plot[i]); } @@ -1962,12 +2100,12 @@ void HandleInput(ImPlot3DPlot& plot) { plot.ContextClick = false; // Handle reset rotation with left mouse double click - if (plot.Held && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Right)) { + if (plot.Held && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Right) && !plot.IsRotationLocked()) { plot.RotationAnimationEnd = plot.Rotation; // Calculate rotation to align the z-axis with the camera direction if (hovered_plane == -1) { - plot.RotationAnimationEnd = init_rotation; + plot.RotationAnimationEnd = plot.InitialRotation; } else { // Compute plane normal ImPlot3DPoint axis_normal = ImPlot3DPoint(0.0f, 0.0f, 0.0f); @@ -1981,7 +2119,8 @@ void HandleInput(ImPlot3DPlot& plot) { if (hovered_plane != 2) { // Compute rotation to point z-axis up - ImPlot3DQuat align_up = ImPlot3DQuat::FromTwoVectors(plot.RotationAnimationEnd * ImPlot3DPoint(0.0f, 0.0f, 1.0f), ImPlot3DPoint(0.0f, 1.0f, 0.0f)); + ImPlot3DQuat align_up = + ImPlot3DQuat::FromTwoVectors(plot.RotationAnimationEnd * ImPlot3DPoint(0.0f, 0.0f, 1.0f), ImPlot3DPoint(0.0f, 1.0f, 0.0f)); plot.RotationAnimationEnd = align_up * plot.RotationAnimationEnd; } else { // Find the axis most aligned with the up direction @@ -2005,7 +2144,7 @@ void HandleInput(ImPlot3DPlot& plot) { // Find the candidate with the maximum dot product AxisAlignment* best_candidate = &candidates[0]; - for (int i = 1; i < 4; ++i) { + for (int i = 1; i < 4; i++) { if (candidates[i].dot > best_candidate->dot) { best_candidate = &candidates[i]; } @@ -2017,16 +2156,12 @@ void HandleInput(ImPlot3DPlot& plot) { } } - // Compute the angular distance between current and target rotation - float dot_product = ImClamp(plot.Rotation.Dot(plot.RotationAnimationEnd), -1.0f, 1.0f); - float angle = 2.0f * acosf(fabsf(dot_product)); - - // Calculate animation time for constant the angular velocity - plot.AnimationTime = angle / ANIMATION_ANGULAR_VELOCITY; + // Calculate animation time + plot.AnimationTime = CalcAnimationTime(plot.Rotation, plot.RotationAnimationEnd); } // Handle rotation with left mouse dragging - if (plot.Held && ImGui::IsMouseDown(ImGuiMouseButton_Right)) { + if (plot.Held && ImGui::IsMouseDown(ImGuiMouseButton_Right) && !plot.IsRotationLocked()) { ImVec2 delta(IO.MouseDelta.x, IO.MouseDelta.y); // Map delta to rotation angles (in radians) @@ -2043,46 +2178,49 @@ void HandleInput(ImPlot3DPlot& plot) { } // Handle zoom with mouse wheel - if (plot.Hovered && (ImGui::IsMouseDown(ImGuiMouseButton_Middle) || IO.MouseWheel != 0)) { - float delta = ImGui::IsMouseDown(ImGuiMouseButton_Middle) ? (-0.01f * IO.MouseDelta.y) : (-0.1f * IO.MouseWheel); - float zoom = 1.0f + delta; - for (int i = 0; i < 3; i++) { - ImPlot3DAxis& axis = plot.Axes[i]; - float size = axis.Range.Max - axis.Range.Min; - float new_min, new_max; - if (hovered_axis != -1 || hovered_plane != -1) { - // If mouse over the plot box, zoom around the mouse plot position - float new_size = size * zoom; + if (plot.Hovered) { + ImGui::SetKeyOwner(ImGuiKey_MouseWheelY, plot.ID); + if (ImGui::IsMouseDown(ImGuiMouseButton_Middle) || IO.MouseWheel != 0.0f) { + float delta = ImGui::IsMouseDown(ImGuiMouseButton_Middle) ? (-0.01f * IO.MouseDelta.y) : (-0.1f * IO.MouseWheel); + float zoom = 1.0f + delta; + for (int i = 0; i < 3; i++) { + ImPlot3DAxis& axis = plot.Axes[i]; + float size = axis.Range.Max - axis.Range.Min; + float new_min, new_max; + if (hovered_axis != -1 || hovered_plane != -1) { + // If mouse over the plot box, zoom around the mouse plot position + float new_size = size * zoom; - // Calculate offset ratio of the mouse position relative to the axis range - float offset = mouse_pos_plot[i] - axis.Range.Min; - float ratio = offset / size; + // Calculate offset ratio of the mouse position relative to the axis range + float offset = mouse_pos_plot[i] - axis.Range.Min; + float ratio = offset / size; - // Adjust the axis range to zoom around the mouse position - new_min = mouse_pos_plot[i] - new_size * ratio; - new_max = mouse_pos_plot[i] + new_size * (1.0f - ratio); - } else { - // If mouse is not over the plot box, zoom around the plot center - float center = (axis.Range.Min + axis.Range.Max) * 0.5f; + // Adjust the axis range to zoom around the mouse position + new_min = mouse_pos_plot[i] - new_size * ratio; + new_max = mouse_pos_plot[i] + new_size * (1.0f - ratio); + } else { + // If mouse is not over the plot box, zoom around the plot center + float center = (axis.Range.Min + axis.Range.Max) * 0.5f; - // Adjust the axis range to zoom around plot center - new_min = center - zoom * size * 0.5f; - new_max = center + zoom * size * 0.5f; - } - - // Set new range after zoom - if (plot.Axes[i].Hovered) { - if (!plot.Axes[i].IsInputLocked()) { - plot.Axes[i].SetMin(new_min); - plot.Axes[i].SetMax(new_max); + // Adjust the axis range to zoom around plot center + new_min = center - zoom * size * 0.5f; + new_max = center + zoom * size * 0.5f; } - plot.Axes[i].Held = true; - } - // If no axis was held before (user started zoom in this frame), set the held edge/plane indices - if (!any_axis_held) { - plot.HeldEdgeIdx = hovered_edge_idx; - plot.HeldPlaneIdx = hovered_plane_idx; + // Set new range after zoom + if (plot.Axes[i].Hovered) { + if (!plot.Axes[i].IsInputLocked()) { + plot.Axes[i].SetMin(new_min); + plot.Axes[i].SetMax(new_max); + } + plot.Axes[i].Held = true; + } + + // If no axis was held before (user started zoom in this frame), set the held edge/plane indices + if (!any_axis_held) { + plot.HeldEdgeIdx = hovered_edge_idx; + plot.HeldPlaneIdx = hovered_plane_idx; + } } } } @@ -2188,9 +2326,7 @@ void SetupLock() { // [SECTION] Miscellaneous //----------------------------------------------------------------------------- -ImDrawList* GetPlotDrawList() { - return ImGui::GetWindowDrawList(); -} +ImDrawList* GetPlotDrawList() { return ImGui::GetWindowDrawList(); } //----------------------------------------------------------------------------- // [SECTION] Styles @@ -2203,25 +2339,24 @@ struct ImPlot3DStyleVarInfo { void* GetVarPtr(ImPlot3DStyle* style) const { return (void*)((unsigned char*)style + Offset); } }; -static const ImPlot3DStyleVarInfo GPlot3DStyleVarInfo[] = - { - // Item style - {ImGuiDataType_Float, 1, (ImU32)offsetof(ImPlot3DStyle, LineWeight)}, // ImPlot3DStyleVar_LineWeight - {ImGuiDataType_S32, 1, (ImU32)offsetof(ImPlot3DStyle, Marker)}, // ImPlot3DStyleVar_Marker - {ImGuiDataType_Float, 1, (ImU32)offsetof(ImPlot3DStyle, MarkerSize)}, // ImPlot3DStyleVar_MarkerSize - {ImGuiDataType_Float, 1, (ImU32)offsetof(ImPlot3DStyle, MarkerWeight)}, // ImPlot3DStyleVar_MarkerWeight - {ImGuiDataType_Float, 1, (ImU32)offsetof(ImPlot3DStyle, FillAlpha)}, // ImPlot3DStyleVar_FillAlpha +static const ImPlot3DStyleVarInfo GPlot3DStyleVarInfo[] = { + // Item style + {ImGuiDataType_Float, 1, (ImU32)offsetof(ImPlot3DStyle, LineWeight)}, // ImPlot3DStyleVar_LineWeight + {ImGuiDataType_S32, 1, (ImU32)offsetof(ImPlot3DStyle, Marker)}, // ImPlot3DStyleVar_Marker + {ImGuiDataType_Float, 1, (ImU32)offsetof(ImPlot3DStyle, MarkerSize)}, // ImPlot3DStyleVar_MarkerSize + {ImGuiDataType_Float, 1, (ImU32)offsetof(ImPlot3DStyle, MarkerWeight)}, // ImPlot3DStyleVar_MarkerWeight + {ImGuiDataType_Float, 1, (ImU32)offsetof(ImPlot3DStyle, FillAlpha)}, // ImPlot3DStyleVar_FillAlpha - // Plot style - {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, PlotDefaultSize)}, // ImPlot3DStyleVar_Plot3DDefaultSize - {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, PlotMinSize)}, // ImPlot3DStyleVar_Plot3DMinSize - {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, PlotPadding)}, // ImPlot3DStyleVar_Plot3DPadding + // Plot style + {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, PlotDefaultSize)}, // ImPlot3DStyleVar_Plot3DDefaultSize + {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, PlotMinSize)}, // ImPlot3DStyleVar_Plot3DMinSize + {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, PlotPadding)}, // ImPlot3DStyleVar_Plot3DPadding - // Label style - {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, LabelPadding)}, // ImPlot3DStyleVar_LabelPaddine - {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, LegendPadding)}, // ImPlot3DStyleVar_LegendPadding - {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, LegendInnerPadding)}, // ImPlot3DStyleVar_LegendInnerPadding - {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, LegendSpacing)}, // ImPlot3DStyleVar_LegendSpacing + // Label style + {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, LabelPadding)}, // ImPlot3DStyleVar_LabelPaddine + {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, LegendPadding)}, // ImPlot3DStyleVar_LegendPadding + {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, LegendInnerPadding)}, // ImPlot3DStyleVar_LegendInnerPadding + {ImGuiDataType_Float, 2, (ImU32)offsetof(ImPlot3DStyle, LegendSpacing)}, // ImPlot3DStyleVar_LegendSpacing }; static const ImPlot3DStyleVarInfo* GetPlotStyleVarInfo(ImPlot3DStyleVar idx) { @@ -2231,6 +2366,7 @@ static const ImPlot3DStyleVarInfo* GetPlotStyleVarInfo(ImPlot3DStyleVar idx) { } ImPlot3DStyle& GetStyle() { return GImPlot3D->Style; } +void SetStyle(const ImPlot3DStyle& style) { GImPlot3D->Style = style; } void StyleColorsAuto(ImPlot3DStyle* dst) { ImPlot3DStyle* style = dst ? dst : &ImPlot3D::GetStyle(); @@ -2406,13 +2542,9 @@ void PopStyleVar(int count) { } } -ImVec4 GetStyleColorVec4(ImPlot3DCol idx) { - return IsColorAuto(idx) ? GetAutoColor(idx) : GImPlot3D->Style.Colors[idx]; -} +ImVec4 GetStyleColorVec4(ImPlot3DCol idx) { return IsColorAuto(idx) ? GetAutoColor(idx) : GImPlot3D->Style.Colors[idx]; } -ImU32 GetStyleColorU32(ImPlot3DCol idx) { - return ImGui::ColorConvertFloat4ToU32(ImPlot3D::GetStyleColorVec4(idx)); -} +ImU32 GetStyleColorU32(ImPlot3DCol idx) { return ImGui::ColorConvertFloat4ToU32(ImPlot3D::GetStyleColorVec4(idx)); } //------------------------------------------------------------------------------ // [SECTION] Colormaps @@ -2424,7 +2556,7 @@ ImPlot3DColormap AddColormap(const char* name, const ImVec4* colormap, int size, IM_ASSERT_USER_ERROR(gp.ColormapData.GetIndex(name) == -1, "The colormap name has already been used!"); ImVector buffer; buffer.resize(size); - for (int i = 0; i < size; ++i) + for (int i = 0; i < size; i++) buffer[i] = ImGui::ColorConvertFloat4ToU32(colormap[i]); return gp.ColormapData.Append(name, buffer.Data, size, qual); } @@ -2485,9 +2617,7 @@ ImU32 NextColormapColorU32() { return col; } -ImVec4 NextColormapColor() { - return ImGui::ColorConvertU32ToFloat4(NextColormapColorU32()); -} +ImVec4 NextColormapColor() { return ImGui::ColorConvertU32ToFloat4(NextColormapColorU32()); } int GetColormapSize(ImPlot3DColormap cmap) { ImPlot3DContext& gp = *GImPlot3D; @@ -2504,9 +2634,7 @@ ImU32 GetColormapColorU32(int idx, ImPlot3DColormap cmap) { return gp.ColormapData.GetKeyColor(cmap, idx); } -ImVec4 GetColormapColor(int idx, ImPlot3DColormap cmap) { - return ImGui::ColorConvertU32ToFloat4(GetColormapColorU32(idx, cmap)); -} +ImVec4 GetColormapColor(int idx, ImPlot3DColormap cmap) { return ImGui::ColorConvertU32ToFloat4(GetColormapColorU32(idx, cmap)); } ImU32 SampleColormapU32(float t, ImPlot3DColormap cmap) { ImPlot3DContext& gp = *GImPlot3D; @@ -2515,8 +2643,74 @@ ImU32 SampleColormapU32(float t, ImPlot3DColormap cmap) { return gp.ColormapData.LerpTable(cmap, t); } -ImVec4 SampleColormap(float t, ImPlot3DColormap cmap) { - return ImGui::ColorConvertU32ToFloat4(SampleColormapU32(t, cmap)); +ImVec4 SampleColormap(float t, ImPlot3DColormap cmap) { return ImGui::ColorConvertU32ToFloat4(SampleColormapU32(t, cmap)); } + +void RenderColorBar(const ImU32* colors, int size, ImDrawList& DrawList, const ImRect& bounds, bool vert, bool reversed, bool continuous) { + const int n = continuous ? size - 1 : size; + ImU32 col1, col2; + if (vert) { + const float step = bounds.GetHeight() / n; + ImRect rect(bounds.Min.x, bounds.Min.y, bounds.Max.x, bounds.Min.y + step); + for (int i = 0; i < n; ++i) { + if (reversed) { + col1 = colors[size - i - 1]; + col2 = continuous ? colors[size - i - 2] : col1; + } else { + col1 = colors[i]; + col2 = continuous ? colors[i + 1] : col1; + } + DrawList.AddRectFilledMultiColor(rect.Min, rect.Max, col1, col1, col2, col2); + rect.TranslateY(step); + } + } else { + const float step = bounds.GetWidth() / n; + ImRect rect(bounds.Min.x, bounds.Min.y, bounds.Min.x + step, bounds.Max.y); + for (int i = 0; i < n; ++i) { + if (reversed) { + col1 = colors[size - i - 1]; + col2 = continuous ? colors[size - i - 2] : col1; + } else { + col1 = colors[i]; + col2 = continuous ? colors[i + 1] : col1; + } + DrawList.AddRectFilledMultiColor(rect.Min, rect.Max, col1, col2, col2, col1); + rect.TranslateX(step); + } + } +} + +bool ColormapSlider(const char* label, float* t, ImVec4* out, const char* format, ImPlot3DColormap cmap) { + *t = ImClamp(*t, 0.0f, 1.0f); + ImGuiContext& G = *GImGui; + ImGuiWindow* Window = G.CurrentWindow; + if (Window->SkipItems) + return false; + ImPlot3DContext& gp = *GImPlot3D; + cmap = cmap == IMPLOT3D_AUTO ? gp.Style.Colormap : cmap; + IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, "Invalid colormap index!"); + const ImU32* keys = gp.ColormapData.GetKeys(cmap); + const int count = gp.ColormapData.GetKeyCount(cmap); + const bool qual = gp.ColormapData.IsQual(cmap); + const ImVec2 pos = ImGui::GetCurrentWindow()->DC.CursorPos; + const float w = ImGui::CalcItemWidth(); + const float h = ImGui::GetFrameHeight(); + const ImRect rect = ImRect(pos.x, pos.y, pos.x + w, pos.y + h); + RenderColorBar(keys, count, *ImGui::GetWindowDrawList(), rect, false, false, !qual); + const ImU32 grab = CalcTextColor(gp.ColormapData.LerpTable(cmap, *t)); + // const ImU32 text = CalcTextColor(gp.ColormapData.LerpTable(cmap,0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBg, IM_COL32_BLACK_TRANS); + ImGui::PushStyleColor(ImGuiCol_FrameBgActive, IM_COL32_BLACK_TRANS); + ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImVec4(1, 1, 1, 0.1f)); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, grab); + ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, grab); + ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 2); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0); + const bool changed = ImGui::SliderFloat(label, t, 0, 1, format); + ImGui::PopStyleColor(5); + ImGui::PopStyleVar(2); + if (out != nullptr) + *out = ImGui::ColorConvertU32ToFloat4(gp.ColormapData.LerpTable(cmap, *t)); + return changed; } //----------------------------------------------------------------------------- @@ -2532,18 +2726,35 @@ void InitializeContext(ImPlot3DContext* ctx) { const ImU32 Deep[] = {4289753676, 4283598045, 4285048917, 4283584196, 4289950337, 4284512403, 4291005402, 4287401100, 4285839820, 4291671396}; const ImU32 Dark[] = {4280031972, 4290281015, 4283084621, 4288892568, 4278222847, 4281597951, 4280833702, 4290740727, 4288256409}; const ImU32 Pastel[] = {4289639675, 4293119411, 4291161036, 4293184478, 4289124862, 4291624959, 4290631909, 4293712637, 4294111986}; - const ImU32 Paired[] = {4293119554, 4290017311, 4287291314, 4281114675, 4288256763, 4280031971, 4285513725, 4278222847, 4292260554, 4288298346, 4288282623, 4280834481}; - const ImU32 Viridis[] = {4283695428, 4285867080, 4287054913, 4287455029, 4287526954, 4287402273, 4286883874, 4285579076, 4283552122, 4280737725, 4280674301}; - const ImU32 Plasma[] = {4287039501, 4288480321, 4289200234, 4288941455, 4287638193, 4286072780, 4284638433, 4283139314, 4281771772, 4280667900, 4280416752}; - const ImU32 Hot[] = {4278190144, 4278190208, 4278190271, 4278190335, 4278206719, 4278223103, 4278239231, 4278255615, 4283826175, 4289396735, 4294967295}; - const ImU32 Cool[] = {4294967040, 4294960666, 4294954035, 4294947661, 4294941030, 4294934656, 4294928025, 4294921651, 4294915020, 4294908646, 4294902015}; - const ImU32 Pink[] = {4278190154, 4282532475, 4284308894, 4285690554, 4286879686, 4287870160, 4288794330, 4289651940, 4291685869, 4293392118, 4294967295}; - const ImU32 Jet[] = {4289331200, 4294901760, 4294923520, 4294945280, 4294967040, 4289396565, 4283826090, 4278255615, 4278233855, 4278212095, 4278190335}; - const ImU32 Twilight[] = {IM_RGB(226, 217, 226), IM_RGB(166, 191, 202), IM_RGB(109, 144, 192), IM_RGB(95, 88, 176), IM_RGB(83, 30, 124), IM_RGB(47, 20, 54), IM_RGB(100, 25, 75), IM_RGB(159, 60, 80), IM_RGB(192, 117, 94), IM_RGB(208, 179, 158), IM_RGB(226, 217, 226)}; - const ImU32 RdBu[] = {IM_RGB(103, 0, 31), IM_RGB(178, 24, 43), IM_RGB(214, 96, 77), IM_RGB(244, 165, 130), IM_RGB(253, 219, 199), IM_RGB(247, 247, 247), IM_RGB(209, 229, 240), IM_RGB(146, 197, 222), IM_RGB(67, 147, 195), IM_RGB(33, 102, 172), IM_RGB(5, 48, 97)}; - const ImU32 BrBG[] = {IM_RGB(84, 48, 5), IM_RGB(140, 81, 10), IM_RGB(191, 129, 45), IM_RGB(223, 194, 125), IM_RGB(246, 232, 195), IM_RGB(245, 245, 245), IM_RGB(199, 234, 229), IM_RGB(128, 205, 193), IM_RGB(53, 151, 143), IM_RGB(1, 102, 94), IM_RGB(0, 60, 48)}; - const ImU32 PiYG[] = {IM_RGB(142, 1, 82), IM_RGB(197, 27, 125), IM_RGB(222, 119, 174), IM_RGB(241, 182, 218), IM_RGB(253, 224, 239), IM_RGB(247, 247, 247), IM_RGB(230, 245, 208), IM_RGB(184, 225, 134), IM_RGB(127, 188, 65), IM_RGB(77, 146, 33), IM_RGB(39, 100, 25)}; - const ImU32 Spectral[] = {IM_RGB(158, 1, 66), IM_RGB(213, 62, 79), IM_RGB(244, 109, 67), IM_RGB(253, 174, 97), IM_RGB(254, 224, 139), IM_RGB(255, 255, 191), IM_RGB(230, 245, 152), IM_RGB(171, 221, 164), IM_RGB(102, 194, 165), IM_RGB(50, 136, 189), IM_RGB(94, 79, 162)}; + const ImU32 Paired[] = {4293119554, 4290017311, 4287291314, 4281114675, 4288256763, 4280031971, + 4285513725, 4278222847, 4292260554, 4288298346, 4288282623, 4280834481}; + const ImU32 Viridis[] = {4283695428, 4285867080, 4287054913, 4287455029, 4287526954, 4287402273, + 4286883874, 4285579076, 4283552122, 4280737725, 4280674301}; + const ImU32 Plasma[] = {4287039501, 4288480321, 4289200234, 4288941455, 4287638193, 4286072780, + 4284638433, 4283139314, 4281771772, 4280667900, 4280416752}; + const ImU32 Hot[] = {4278190144, 4278190208, 4278190271, 4278190335, 4278206719, 4278223103, + 4278239231, 4278255615, 4283826175, 4289396735, 4294967295}; + const ImU32 Cool[] = {4294967040, 4294960666, 4294954035, 4294947661, 4294941030, 4294934656, + 4294928025, 4294921651, 4294915020, 4294908646, 4294902015}; + const ImU32 Pink[] = {4278190154, 4282532475, 4284308894, 4285690554, 4286879686, 4287870160, + 4288794330, 4289651940, 4291685869, 4293392118, 4294967295}; + const ImU32 Jet[] = {4289331200, 4294901760, 4294923520, 4294945280, 4294967040, 4289396565, + 4283826090, 4278255615, 4278233855, 4278212095, 4278190335}; + const ImU32 Twilight[] = {IM_RGB(226, 217, 226), IM_RGB(166, 191, 202), IM_RGB(109, 144, 192), IM_RGB(95, 88, 176), + IM_RGB(83, 30, 124), IM_RGB(47, 20, 54), IM_RGB(100, 25, 75), IM_RGB(159, 60, 80), + IM_RGB(192, 117, 94), IM_RGB(208, 179, 158), IM_RGB(226, 217, 226)}; + const ImU32 RdBu[] = {IM_RGB(103, 0, 31), IM_RGB(178, 24, 43), IM_RGB(214, 96, 77), IM_RGB(244, 165, 130), + IM_RGB(253, 219, 199), IM_RGB(247, 247, 247), IM_RGB(209, 229, 240), IM_RGB(146, 197, 222), + IM_RGB(67, 147, 195), IM_RGB(33, 102, 172), IM_RGB(5, 48, 97)}; + const ImU32 BrBG[] = {IM_RGB(84, 48, 5), IM_RGB(140, 81, 10), IM_RGB(191, 129, 45), IM_RGB(223, 194, 125), + IM_RGB(246, 232, 195), IM_RGB(245, 245, 245), IM_RGB(199, 234, 229), IM_RGB(128, 205, 193), + IM_RGB(53, 151, 143), IM_RGB(1, 102, 94), IM_RGB(0, 60, 48)}; + const ImU32 PiYG[] = {IM_RGB(142, 1, 82), IM_RGB(197, 27, 125), IM_RGB(222, 119, 174), IM_RGB(241, 182, 218), + IM_RGB(253, 224, 239), IM_RGB(247, 247, 247), IM_RGB(230, 245, 208), IM_RGB(184, 225, 134), + IM_RGB(127, 188, 65), IM_RGB(77, 146, 33), IM_RGB(39, 100, 25)}; + const ImU32 Spectral[] = {IM_RGB(158, 1, 66), IM_RGB(213, 62, 79), IM_RGB(244, 109, 67), IM_RGB(253, 174, 97), + IM_RGB(254, 224, 139), IM_RGB(255, 255, 191), IM_RGB(230, 245, 152), IM_RGB(171, 221, 164), + IM_RGB(102, 194, 165), IM_RGB(50, 136, 189), IM_RGB(94, 79, 162)}; const ImU32 Greys[] = {IM_COL32_WHITE, IM_COL32_BLACK}; IMPLOT3D_APPEND_CMAP(Deep, true); @@ -2568,6 +2779,7 @@ void ResetContext(ImPlot3DContext* ctx) { ctx->Plots.Clear(); ctx->CurrentPlot = nullptr; ctx->CurrentItems = nullptr; + ctx->CurrentItem = nullptr; ctx->NextItemData.Reset(); ctx->Style = ImPlot3DStyle(); } @@ -2576,13 +2788,9 @@ void ResetContext(ImPlot3DContext* ctx) { // [SECTION] Style Utils //----------------------------------------------------------------------------- -bool IsColorAuto(const ImVec4& col) { - return col.w == -1.0f; -} +bool IsColorAuto(const ImVec4& col) { return col.w == -1.0f; } -bool IsColorAuto(ImPlot3DCol idx) { - return IsColorAuto(GImPlot3D->Style.Colors[idx]); -} +bool IsColorAuto(ImPlot3DCol idx) { return IsColorAuto(GImPlot3D->Style.Colors[idx]); } ImVec4 GetAutoColor(ImPlot3DCol idx) { switch (idx) { @@ -2607,21 +2815,8 @@ ImVec4 GetAutoColor(ImPlot3DCol idx) { const char* GetStyleColorName(ImPlot3DCol idx) { static const char* color_names[ImPlot3DCol_COUNT] = { - "Line", - "Fill", - "MarkerOutline", - "MarkerFill", - "TitleText", - "InlayText", - "FrameBg", - "PlotBg", - "PlotBorder", - "LegendBg", - "LegendBorder", - "LegendText", - "AxisText", - "AxisGrid", - "AxisTick", + "Line", "Fill", "MarkerOutline", "MarkerFill", "TitleText", "InlayText", "FrameBg", "PlotBg", + "PlotBorder", "LegendBg", "LegendBorder", "LegendText", "AxisText", "AxisGrid", "AxisTick", }; return color_names[idx]; } @@ -2704,13 +2899,9 @@ ImPlot3DPoint ImPlot3DPoint::Normalized() const { return ImPlot3DPoint(x / l, y / l, z / l); } -ImPlot3DPoint operator*(float lhs, const ImPlot3DPoint& rhs) { - return ImPlot3DPoint(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z); -} +ImPlot3DPoint operator*(float lhs, const ImPlot3DPoint& rhs) { return ImPlot3DPoint(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z); } -bool ImPlot3DPoint::IsNaN() const { - return ImPlot3D::ImNan(x) || ImPlot3D::ImNan(y) || ImPlot3D::ImNan(z); -} +bool ImPlot3DPoint::IsNaN() const { return ImPlot3D::ImNan(x) || ImPlot3D::ImNan(y) || ImPlot3D::ImNan(z); } //----------------------------------------------------------------------------- // [SECTION] ImPlot3DBox @@ -2726,9 +2917,7 @@ void ImPlot3DBox::Expand(const ImPlot3DPoint& point) { } bool ImPlot3DBox::Contains(const ImPlot3DPoint& point) const { - return (point.x >= Min.x && point.x <= Max.x) && - (point.y >= Min.y && point.y <= Max.y) && - (point.z >= Min.z && point.z <= Max.z); + return (point.x >= Min.x && point.x <= Max.x) && (point.y >= Min.y && point.y <= Max.y) && (point.z >= Min.z && point.z <= Max.z); } bool ImPlot3DBox::ClipLineSegment(const ImPlot3DPoint& p0, const ImPlot3DPoint& p1, ImPlot3DPoint& p0_clipped, ImPlot3DPoint& p1_clipped) const { @@ -2802,9 +2991,7 @@ void ImPlot3DRange::Expand(float value) { Max = ImMax(Max, value); } -bool ImPlot3DRange::Contains(float value) const { - return value >= Min && value <= Max; -} +bool ImPlot3DRange::Contains(float value) const { return value >= Min && value <= Max; } //----------------------------------------------------------------------------- // [SECTION] ImPlot3DQuat @@ -2844,8 +3031,7 @@ ImPlot3DQuat ImPlot3DQuat::FromTwoVectors(const ImPlot3DPoint& v0, const ImPlot3 // Handle edge case: if vectors are opposite if (ImFabs(normalized_dot + 1.0f) < epsilon) { // v0 and v1 are opposite; choose an arbitrary orthogonal axis - ImPlot3DPoint arbitrary_axis = ImFabs(v0.x) > ImFabs(v0.z) ? ImPlot3DPoint(-v0.y, v0.x, 0.0f) - : ImPlot3DPoint(0.0f, -v0.z, v0.y); + ImPlot3DPoint arbitrary_axis = ImFabs(v0.x) > ImFabs(v0.z) ? ImPlot3DPoint(-v0.y, v0.x, 0.0f) : ImPlot3DPoint(0.0f, -v0.z, v0.y); arbitrary_axis.Normalize(); q.x = arbitrary_axis.x; q.y = arbitrary_axis.y; @@ -2868,18 +3054,24 @@ ImPlot3DQuat ImPlot3DQuat::FromTwoVectors(const ImPlot3DPoint& v0, const ImPlot3 return q; } -float ImPlot3DQuat::Length() const { - return ImSqrt(x * x + y * y + z * z + w * w); +ImPlot3DQuat ImPlot3DQuat::FromElAz(float elevation, float azimuth) { + // Create quaternions for azimuth and elevation + ImPlot3DQuat azimuth_quat(azimuth, ImPlot3DPoint(0.0f, 0.0f, 1.0f)); // Rotate around Z-axis + ImPlot3DQuat elevation_quat(elevation, ImPlot3DPoint(1.0f, 0.0f, 0.0f)); // Rotate around X-axis + ImPlot3DQuat zero_quat(-IM_PI / 2, ImPlot3DPoint(1.0f, 0.0f, 0.0f)); // Rotate to zero azimuth/elevation orientation + + // Combine rotations + return elevation_quat * zero_quat * azimuth_quat; } +float ImPlot3DQuat::Length() const { return ImSqrt(x * x + y * y + z * z + w * w); } + ImPlot3DQuat ImPlot3DQuat::Normalized() const { float l = Length(); return ImPlot3DQuat(x / l, y / l, z / l, w / l); } -ImPlot3DQuat ImPlot3DQuat::Conjugate() const { - return ImPlot3DQuat(-x, -y, -z, w); -} +ImPlot3DQuat ImPlot3DQuat::Conjugate() const { return ImPlot3DQuat(-x, -y, -z, w); } ImPlot3DQuat ImPlot3DQuat::Inverse() const { float l_squared = x * x + y * y + z * z + w * w; @@ -2887,11 +3079,8 @@ ImPlot3DQuat ImPlot3DQuat::Inverse() const { } ImPlot3DQuat ImPlot3DQuat::operator*(const ImPlot3DQuat& rhs) const { - return ImPlot3DQuat( - w * rhs.x + x * rhs.w + y * rhs.z - z * rhs.y, - w * rhs.y - x * rhs.z + y * rhs.w + z * rhs.x, - w * rhs.z + x * rhs.y - y * rhs.x + z * rhs.w, - w * rhs.w - x * rhs.x - y * rhs.y - z * rhs.z); + return ImPlot3DQuat(w * rhs.x + x * rhs.w + y * rhs.z - z * rhs.y, w * rhs.y - x * rhs.z + y * rhs.w + z * rhs.x, + w * rhs.z + x * rhs.y - y * rhs.x + z * rhs.w, w * rhs.w - x * rhs.x - y * rhs.y - z * rhs.z); } ImPlot3DQuat& ImPlot3DQuat::Normalize() { @@ -2915,13 +3104,9 @@ ImPlot3DPoint ImPlot3DQuat::operator*(const ImPlot3DPoint& point) const { return point + (uv * w * 2.0f) + (uuv * 2.0f); } -bool ImPlot3DQuat::operator==(const ImPlot3DQuat& rhs) const { - return x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w; -} +bool ImPlot3DQuat::operator==(const ImPlot3DQuat& rhs) const { return x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w; } -bool ImPlot3DQuat::operator!=(const ImPlot3DQuat& rhs) const { - return !(*this == rhs); -} +bool ImPlot3DQuat::operator!=(const ImPlot3DQuat& rhs) const { return !(*this == rhs); } ImPlot3DQuat ImPlot3DQuat::Slerp(const ImPlot3DQuat& q1, const ImPlot3DQuat& q2, float t) { // Clamp t to [0, 1] @@ -2939,12 +3124,7 @@ ImPlot3DQuat ImPlot3DQuat::Slerp(const ImPlot3DQuat& q1, const ImPlot3DQuat& q2, // If the quaternions are very close, use linear interpolation to avoid numerical instability if (dot > 0.9995f) { - return ImPlot3DQuat( - q1.x + t * (q2_.x - q1.x), - q1.y + t * (q2_.y - q1.y), - q1.z + t * (q2_.z - q1.z), - q1.w + t * (q2_.w - q1.w)) - .Normalized(); + return ImPlot3DQuat(q1.x + t * (q2_.x - q1.x), q1.y + t * (q2_.y - q1.y), q1.z + t * (q2_.z - q1.z), q1.w + t * (q2_.w - q1.w)).Normalized(); } // Compute the angle and the interpolation factors @@ -2957,16 +3137,10 @@ ImPlot3DQuat ImPlot3DQuat::Slerp(const ImPlot3DQuat& q1, const ImPlot3DQuat& q2, float s2 = sin_theta / sin_theta_0; // Interpolate and return the result - return ImPlot3DQuat( - s1 * q1.x + s2 * q2_.x, - s1 * q1.y + s2 * q2_.y, - s1 * q1.z + s2 * q2_.z, - s1 * q1.w + s2 * q2_.w); + return ImPlot3DQuat(s1 * q1.x + s2 * q2_.x, s1 * q1.y + s2 * q2_.y, s1 * q1.z + s2 * q2_.z, s1 * q1.w + s2 * q2_.w); } -float ImPlot3DQuat::Dot(const ImPlot3DQuat& rhs) const { - return x * rhs.x + y * rhs.y + z * rhs.z + w * rhs.w; -} +float ImPlot3DQuat::Dot(const ImPlot3DQuat& rhs) const { return x * rhs.x + y * rhs.y + z * rhs.z + w * rhs.w; } //----------------------------------------------------------------------------- // [SECTION] ImDrawList3D @@ -2996,19 +3170,47 @@ void ImDrawList3D::PrimUnreserve(int idx_count, int vtx_count) { ZBuffer.shrink(ZBuffer.Size - idx_count / 3); } +void ImDrawList3D::SetTexture(ImTextureRef tex_ref) { + if (_TextureBuffer.empty()) { + // First texture assignment + _TextureBuffer.push_back({tex_ref, _VtxCurrentIdx}); + return; + } + + ImTextureBufferItem& prev_item = _TextureBuffer.back(); + if (prev_item.VtxIdx == _VtxCurrentIdx) { + // Same vertex index: update existing texture ID + prev_item.TexRef = tex_ref; + + // If the previous texture was the same, remove current texture + if (_TextureBuffer.Size >= 2) { + if (_TextureBuffer[_TextureBuffer.Size - 2].TexRef == tex_ref) { + _TextureBuffer.pop_back(); + } + } + } else if (prev_item.TexRef != tex_ref) { + // New vertex index and different texture: insert new item + _TextureBuffer.push_back({tex_ref, _VtxCurrentIdx}); + } +} + +void ImDrawList3D::ResetTexture() { SetTexture(ImTextureID(0)); } + +#ifdef IMGUI_HAS_TEXTURES +#define SET_TEX_REF(cmd, tex_ref) (cmd).TexRef = (tex_ref) +#define GET_TEX_REF(cmd) (cmd).TexRef +#else +#define SET_TEX_REF(cmd, tex_ref) (cmd).TextureId = (tex_ref) +#define GET_TEX_REF(cmd) (cmd).TextureId +#endif + void ImDrawList3D::SortedMoveToImGuiDrawList() { ImDrawList& draw_list = *ImGui::GetWindowDrawList(); const int tri_count = ZBuffer.Size; if (tri_count == 0) { - // No triangles, just clear and return - VtxBuffer.clear(); - IdxBuffer.clear(); - ZBuffer.clear(); - _VtxCurrentIdx = 0; - _VtxWritePtr = VtxBuffer.Data; - _IdxWritePtr = IdxBuffer.Data; - _ZWritePtr = ZBuffer.Data; + // No triangles, just reset buffers and return + ResetBuffers(); return; } @@ -3024,13 +3226,11 @@ void ImDrawList3D::SortedMoveToImGuiDrawList() { } // Sort by z (distance from viewer) - ImQsort(tris, (size_t)tri_count, sizeof(TriRef), - [](const void* a, const void* b) { - float za = ((const TriRef*)a)->z; - float zb = ((const TriRef*)b)->z; - return (za < zb) ? -1 : (za > zb) ? 1 - : 0; - }); + ImQsort(tris, (size_t)tri_count, sizeof(TriRef), [](const void* a, const void* b) { + float za = ((const TriRef*)a)->z; + float zb = ((const TriRef*)b)->z; + return (za < zb) ? -1 : (za > zb) ? 1 : 0; + }); // Reserve space in the ImGui draw list draw_list.PrimReserve(IdxBuffer.Size, VtxBuffer.Size); @@ -3045,7 +3245,8 @@ void ImDrawList3D::SortedMoveToImGuiDrawList() { unsigned int max_index_allowed = MaxIdx() - idx_offset; // Copy indices with triangle sorting based on distance from viewer - ImDrawIdx* idx_out = draw_list._IdxWritePtr; + ImDrawIdx* idx_out_begin = draw_list._IdxWritePtr; + ImDrawIdx* idx_out = idx_out_begin; ImDrawIdx* idx_in = IdxBuffer.Data; for (int i = 0; i < tri_count; i++) { int tri_i = tris[i].tri_idx; @@ -3056,7 +3257,7 @@ void ImDrawList3D::SortedMoveToImGuiDrawList() { // Check if after adding offset any of these indices exceed max_index_allowed if (i0 > max_index_allowed || i1 > max_index_allowed || i2 > max_index_allowed) - break; + continue; idx_out[0] = (ImDrawIdx)(i0 + idx_offset); idx_out[1] = (ImDrawIdx)(i1 + idx_offset); @@ -3064,16 +3265,67 @@ void ImDrawList3D::SortedMoveToImGuiDrawList() { idx_out += 3; } - draw_list._IdxWritePtr = idx_out; + ImDrawIdx* idx_out_end = idx_out; + draw_list._IdxWritePtr = idx_out_end; - // Clear local buffers since we've moved them - VtxBuffer.clear(); - IdxBuffer.clear(); - ZBuffer.clear(); - _VtxCurrentIdx = 0; - _VtxWritePtr = VtxBuffer.Data; - _IdxWritePtr = IdxBuffer.Data; - _ZWritePtr = ZBuffer.Data; + // If multiple textures were used (e.g. PlotImage was called), generate multiple ImDrawCmd + if (_TextureBuffer.Size > 1) { + ImTextureRef default_tex = GET_TEX_REF(draw_list._CmdHeader); + ImTextureRef curr_tex = default_tex; + + // Remove elements reserved from PrimReserve + draw_list.CmdBuffer.back().ElemCount -= IdxBuffer.Size; + ImDrawIdx* last_cmd_buffer_idx = idx_out_begin; + + // For each triangle added to the draw_list + for (idx_out = idx_out_begin; idx_out < idx_out_end; idx_out += 3) { + // Get index of first vertex in the triangle + unsigned int idx_in = (unsigned int)(*idx_out - idx_offset); + + // Get the texture for this triangle + const ImTextureRef invalid_tex = ImTextureID(0); + ImTextureRef tri_tex = invalid_tex; + for (int j = 0; j < _TextureBuffer.Size; j++) + if (idx_in >= _TextureBuffer[j].VtxIdx) + tri_tex = _TextureBuffer[j].TexRef; + + // If tri_tex is invalid, the default texture should be used + if (tri_tex == invalid_tex) + tri_tex = default_tex; + + if (tri_tex != curr_tex) { + // Update element count of previous draw cmd + draw_list.CmdBuffer.back().ElemCount += (unsigned int)(idx_out - last_cmd_buffer_idx); + last_cmd_buffer_idx = idx_out; + + // Set custom texture + curr_tex = tri_tex; + SET_TEX_REF(draw_list._CmdHeader, curr_tex); + + // Add new draw cmd for the new texture + ImDrawCmd draw_cmd; + draw_cmd.ClipRect = draw_list._CmdHeader.ClipRect; + SET_TEX_REF(draw_cmd, GET_TEX_REF(draw_list._CmdHeader)); + draw_cmd.VtxOffset = draw_list._CmdHeader.VtxOffset; + draw_cmd.IdxOffset = (unsigned int)(idx_out - draw_list.IdxBuffer.Data); + draw_list.CmdBuffer.push_back(draw_cmd); + } + } + // Flush last elements to cmd buffer + draw_list.CmdBuffer.back().ElemCount += (unsigned int)(&draw_list.IdxBuffer.back() - last_cmd_buffer_idx + 1); + + // Check if the last texture was not the default texture + if (curr_tex != default_tex) { + // Restore default texture + SET_TEX_REF(draw_list._CmdHeader, default_tex); + + // Flush last draw cmd with custom texture + draw_list.AddDrawCmd(); + } + } + + // Reset buffers since we've moved them + ResetBuffers(); IM_FREE(tris); } @@ -3102,6 +3354,7 @@ void ImPlot3DAxis::ApplyFit() { Range.Max += 0.5; Range.Min -= 0.5; } + Constrain(); FitExtents.Min = HUGE_VAL; FitExtents.Max = -HUGE_VAL; } @@ -3117,19 +3370,13 @@ void ImPlot3DPlot::ExtendFit(const ImPlot3DPoint& point) { } } -ImPlot3DPoint ImPlot3DPlot::RangeMin() const { - return ImPlot3DPoint(Axes[0].Range.Min, Axes[1].Range.Min, Axes[2].Range.Min); -} +ImPlot3DPoint ImPlot3DPlot::RangeMin() const { return ImPlot3DPoint(Axes[0].Range.Min, Axes[1].Range.Min, Axes[2].Range.Min); } -ImPlot3DPoint ImPlot3DPlot::RangeMax() const { - return ImPlot3DPoint(Axes[0].Range.Max, Axes[1].Range.Max, Axes[2].Range.Max); -} +ImPlot3DPoint ImPlot3DPlot::RangeMax() const { return ImPlot3DPoint(Axes[0].Range.Max, Axes[1].Range.Max, Axes[2].Range.Max); } ImPlot3DPoint ImPlot3DPlot::RangeCenter() const { - return ImPlot3DPoint( - (Axes[0].Range.Min + Axes[0].Range.Max) * 0.5f, - (Axes[1].Range.Min + Axes[1].Range.Max) * 0.5f, - (Axes[2].Range.Min + Axes[2].Range.Max) * 0.5f); + return ImPlot3DPoint((Axes[0].Range.Min + Axes[0].Range.Max) * 0.5f, (Axes[1].Range.Min + Axes[1].Range.Max) * 0.5f, + (Axes[2].Range.Min + Axes[2].Range.Max) * 0.5f); } void ImPlot3DPlot::SetRange(const ImPlot3DPoint& min, const ImPlot3DPoint& max) { @@ -3138,9 +3385,7 @@ void ImPlot3DPlot::SetRange(const ImPlot3DPoint& min, const ImPlot3DPoint& max) Axes[2].SetRange(min.z, max.z); } -float ImPlot3DPlot::GetBoxZoom() const { - return ImMin(PlotRect.GetWidth(), PlotRect.GetHeight()) / 1.8f; -} +float ImPlot3DPlot::GetBoxZoom() const { return ImMin(PlotRect.GetWidth(), PlotRect.GetHeight()) / 1.8f; } //----------------------------------------------------------------------------- // [SECTION] ImPlot3DStyle @@ -3167,4 +3412,328 @@ ImPlot3DStyle::ImPlot3DStyle() { Colormap = ImPlot3DColormap_Deep; }; +//----------------------------------------------------------------------------- +// [SECTION] Metrics +//----------------------------------------------------------------------------- + +void ShowTicksMetrics(const ImPlot3DTicker& ticker) { ImGui::BulletText("Size: %d", ticker.TickCount()); } + +void ShowAxisMetrics(const ImPlot3DAxis& axis) { + ImGui::BulletText("Label: %s", axis.GetLabel()); + ImGui::BulletText("Flags: 0x%08X", axis.Flags); + ImGui::BulletText("Range: [%f,%f]", axis.Range.Min, axis.Range.Max); + + ImGui::BulletText("ShowDefaultTicks: %s", axis.ShowDefaultTicks ? "true" : "false"); + ImGui::BulletText("FitThisFrame: %s", axis.FitThisFrame ? "true" : "false"); + ImGui::BulletText("FitExtents: [%f,%f]", axis.FitExtents.Min, axis.FitExtents.Min); + ImGui::BulletText("ConstraintRange: [%f,%f]", axis.ConstraintRange.Min, axis.ConstraintRange.Min); + ImGui::BulletText("ConstraintZoom: [%f,%f]", axis.ConstraintZoom.Min, axis.ConstraintZoom.Min); + ImGui::BulletText("Hovered: %s", axis.Hovered ? "true" : "false"); + ImGui::BulletText("Held: %s", axis.Held ? "true" : "false"); + + if (ImGui::TreeNode("Ticks")) { + ShowTicksMetrics(axis.Ticker); + ImGui::TreePop(); + } +} + +void ImPlot3D::ShowMetricsWindow(bool* p_popen) { + static bool show_frame_rects = false; + static bool show_canvas_rects = false; + static bool show_plot_rects = false; + static bool show_plot_box = false; + static bool show_axis_line = false; + static bool show_axis_corner_indexes = false; + static bool show_axis_face_indexes = false; + static bool show_axis_edge_indexes = false; + static bool show_legend_rects = false; + + ImDrawList& fg = *ImGui::GetForegroundDrawList(); + + ImPlot3DContext& gp = *GImPlot3D; + ImGuiIO& io = ImGui::GetIO(); + ImGui::Begin("Metrics (ImPlot3D)", p_popen); + ImGui::Text("ImPlot3D " IMPLOT3D_VERSION); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + ImGui::Text("Mouse Position: [%.0f,%.0f]", io.MousePos.x, io.MousePos.y); + ImGui::Separator(); + if (ImGui::TreeNode("Tools")) { + if (ImGui::Button("Bust Plot Cache")) + BustPlotCache(); + ImGui::SameLine(); + if (ImGui::Button("Bust Item Cache")) + BustItemCache(); + ImGui::Checkbox("Show Frame Rects", &show_frame_rects); + ImGui::Checkbox("Show Canvas Rects", &show_canvas_rects); + ImGui::Checkbox("Show Plot Rects", &show_plot_rects); + ImGui::Checkbox("Show Plot Box", &show_plot_box); + ImGui::Checkbox("Show Axis Line", &show_axis_line); + ImGui::Checkbox("Show Axis Corner Indexes", &show_axis_corner_indexes); + ImGui::Checkbox("Show Axis Face Indexes", &show_axis_face_indexes); + ImGui::Checkbox("Show Axis Edge Indexes", &show_axis_edge_indexes); + ImGui::Checkbox("Show Legend Rects", &show_legend_rects); + ImGui::TreePop(); + } + const int n_plots = gp.Plots.GetBufSize(); + bool active_faces[3]; + ImVec2 corners_pix[8]; + ImPlot3DPoint corners[8]; + int plane_2d; + int axis_corners[3][2]; + char buff[16]; + // Enum used to indicate how a certain type will be displayed + enum class DisplayedType { + Hidden, // Hidden type that is not displayed. Used when the object should not be displayed. Will be used when: + // 1. 2D plot and this type should not be used, + // 2. The flag show_plot_box is disabled + Active, // Part of the faces of the box that are active + NotActive // Part of the faces of the box that are not active when show_plot_box is active + }; + + // Render rectangles + for (int p = 0; p < n_plots; ++p) { + ImPlot3DPlot& plot = *gp.Plots.GetByIndex(p); + if (show_frame_rects) + fg.AddRect(plot.FrameRect.Min, plot.FrameRect.Max, IM_COL32(255, 0, 255, 255)); + if (show_canvas_rects) + fg.AddRect(plot.CanvasRect.Min, plot.CanvasRect.Max, IM_COL32(0, 255, 255, 255)); + if (show_plot_rects) + fg.AddRect(plot.PlotRect.Min, plot.PlotRect.Max, IM_COL32(255, 255, 0, 255)); + if (show_plot_box || show_axis_line || show_axis_corner_indexes || show_axis_face_indexes || show_axis_edge_indexes) + GetAxesParameters(plot, active_faces, corners_pix, corners, plane_2d, axis_corners); + if (show_plot_box || show_axis_edge_indexes) { + // Determine which display type each of the edges are + DisplayedType edge_types[12]; + for (int e = 0; e < 12; e++) { + if (plane_2d == -1 && show_plot_box) + edge_types[e] = DisplayedType::NotActive; + else + edge_types[e] = DisplayedType::Hidden; + } + for (int a = 0; a < 3; a++) { + int face_idx = a + 3 * active_faces[a]; + for (size_t i = 0; (plane_2d == -1 || a == plane_2d) && i < 4; i++) + edge_types[face_edges[face_idx][i]] = DisplayedType::Active; + } + + // Go through each edge and use the display type + for (int e = 0; e < 12; e++) { + int idx0 = edges[e][0]; + int idx1 = edges[e][1]; + + if (show_plot_box) { + // Draw different lines depending on the type that the renderer thinks it is + if (edge_types[e] == DisplayedType::Active) + fg.AddLine(corners_pix[idx0], corners_pix[idx1], IM_COL32(255, 200, 0, 255)); + else if (edge_types[e] == DisplayedType::NotActive) + fg.AddLine(corners_pix[idx0], corners_pix[idx1], IM_COL32(100, 255, 0, 125)); + // If the render edge type is Hidden then there this edge does not get rendered + } + if (show_axis_edge_indexes) { + if (edge_types[e] == DisplayedType::Active || edge_types[e] == DisplayedType::NotActive) { + // Display the text in the middle between the points and at the same angle between the two points + ImVec2 edge_middle = (corners_pix[idx0] + corners_pix[idx1]) / 2; + ImVec2 point_difference = (corners_pix[idx1] - corners_pix[idx0]); + float angle = ImAtan2(-point_difference.y, point_difference.x); + // Adjust angle to keep labels upright + if (angle > IM_PI * 0.5f) + angle -= IM_PI; + if (angle < -IM_PI * 0.5f) + angle += IM_PI; + + ImFormatString(buff, IM_ARRAYSIZE(buff), "E%d", e); + AddTextRotated(&fg, edge_middle, angle, IM_COL32(200, 0, 0, 200), buff); + } + } + } + } + if (show_axis_line) { + // For each axis plot a line between the axis corners + for (int a = 0; a < 3; a++) { + if (plane_2d != -1 && a == plane_2d) + continue; + int idx0 = axis_corners[a][0]; + int idx1 = axis_corners[a][1]; + + // Draw axis line + ImVec2 axis_start_pix = corners_pix[idx0]; + ImVec2 axis_end_pix = corners_pix[idx1]; + fg.AddLine(axis_start_pix, axis_end_pix, IM_COL32(0, 255, 255, 255)); + } + } + if (show_axis_corner_indexes) { + // Determine which display type each of the corners are + DisplayedType corner_types[8]; + for (int c = 0; c < 8; c++) { + if (plane_2d == -1 && show_plot_box) + corner_types[c] = DisplayedType::NotActive; + else + corner_types[c] = DisplayedType::Hidden; + } + for (int a = 0; a < 3; a++) { + int face_idx = a + 3 * active_faces[a]; + for (size_t i = 0; (plane_2d == -1 || a == plane_2d) && i < 4; i++) + corner_types[faces[face_idx][i]] = DisplayedType::Active; + } + // Go through each corner and use the display type + for (int c = 0; c < 8; c++) { + if (corner_types[c] == DisplayedType::Active || corner_types[c] == DisplayedType::NotActive) { + ImVec2 corner = corners_pix[c]; + ImFormatString(buff, IM_ARRAYSIZE(buff), "C%d", c); + AddTextRotated(&fg, corner, 0, IM_COL32(0, 200, 0, 200), buff); + } + } + } + if (show_axis_face_indexes) { + // Go through each axis and then face to display the face index + for (int a = 0; a < 3; a++) { + for (int f = 0; f < 2; f++) { + if ((plane_2d == -1 || a == plane_2d) && (f == int(active_faces[a]) || show_plot_box)) { + const int face_idx = a + 3 * f; + const int* face_indexes = faces[face_idx]; + // Display the text in the middle of the square by determining the point between two of opposite corner pixels + ImVec2 middle_of_face_sqaure = (corners_pix[face_indexes[0]] + corners_pix[face_indexes[2]]) / 2; + ImFormatString(buff, IM_ARRAYSIZE(buff), "F%d", face_idx); + AddTextRotated(&fg, middle_of_face_sqaure, 0, IM_COL32(0, 200, 200, 200), buff); + } + } + } + } + if (show_legend_rects && plot.Items.GetLegendCount() > 0) + fg.AddRect(plot.Items.Legend.Rect.Min, plot.Items.Legend.Rect.Max, IM_COL32(255, 192, 0, 255)); + } + if (ImGui::TreeNode("Plots", "Plots (%d)", n_plots)) { + for (int p = 0; p < n_plots; ++p) { + ImPlot3DPlot& plot = *gp.Plots.GetByIndex(p); + ImGui::PushID(p); + if (ImGui::TreeNode("Plot", "Plot [0x%08X]", plot.ID)) { + int n_items = plot.Items.GetItemCount(); + if (ImGui::TreeNode("Items", "Items (%d)", n_items)) { + for (int i = 0; i < n_items; ++i) { + ImPlot3DItem* item = plot.Items.GetItemByIndex(i); + ImGui::PushID(i); + if (ImGui::TreeNode("Item", "Item [0x%08X]", item->ID)) { + ImGui::Bullet(); + ImGui::Checkbox("Show", &item->Show); + ImGui::Bullet(); + ImVec4 temp = ImGui::ColorConvertU32ToFloat4(item->Color); + if (ImGui::ColorEdit4("Color", &temp.x, ImGuiColorEditFlags_NoInputs)) + item->Color = ImGui::ColorConvertFloat4ToU32(temp); + + ImGui::BulletText("NameOffset: %d", item->NameOffset); + ImGui::BulletText("Name: %s", item->NameOffset != -1 ? plot.Items.Legend.Labels.Buf.Data + item->NameOffset : "N/A"); + ImGui::BulletText("Hovered: %s", item->LegendHovered ? "true" : "false"); + ImGui::TreePop(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Axes")) { + // Get the axes parameters of this plot and use it to plot + GetAxesParameters(plot, active_faces, corners_pix, corners, plane_2d, axis_corners); + + for (int a = 0; a < 3; ++a) { + if (plane_2d != -1 && plane_2d == a) + continue; + if (ImGui::TreeNode(axis_labels[a])) { + ShowAxisMetrics(plot.Axes[a]); + ImGui::TreePop(); + } + } + + if (plane_2d != -1) + ImGui::BulletText("Plane2D: %d %s", plane_2d, plane_labels[plane_2d]); + else { + int active_corner_index = Active3DFacesToAxisLookupIndex(active_faces); + ImGui::BulletText("3D Active Faces: [%s,%s,%s]=%d", active_faces[0] ? "X-max" : "X-min", active_faces[1] ? "Y-max" : "Y-min", + active_faces[2] ? "Z-max" : "Z-min", active_corner_index); + ImGui::BulletText("3D Active Corner Lookup: [[%d,%d],[%d, %d],[%d, %d]]", axis_corners_lookup_3d[active_corner_index][0][0], + axis_corners_lookup_3d[active_corner_index][0][1], axis_corners_lookup_3d[active_corner_index][1][0], + axis_corners_lookup_3d[active_corner_index][1][1], axis_corners_lookup_3d[active_corner_index][2][0], + axis_corners_lookup_3d[active_corner_index][2][1]); + ImGui::BulletText("3D Active Edges Lookup: [%d,%d,%d]", axis_edges_lookup_3d[active_corner_index][0], + axis_edges_lookup_3d[active_corner_index][1], axis_edges_lookup_3d[active_corner_index][2]); + } + + for (int a = 0; a < 3; a++) + ImGui::BulletText("%s Label Corners: [%d,%d]", axis_labels[a], axis_corners[a][0], axis_corners[a][1]); + for (int c = 0; c < 8; c++) + ImGui::BulletText("Corner %d: [%.2f,%.2f,%.2f] [%.2f,%.2f]", c, corners[c].x, corners[c].y, corners[c].z, corners_pix[c].x, + corners_pix[c].y); + + ImGui::TreePop(); + } + + ImGui::BulletText("Title: %s", plot.HasTitle() ? plot.GetTitle() : "none"); + ImGui::BulletText("Flags: 0x%08X", plot.Flags); + ImGui::BulletText("Initialized: %s", plot.Initialized ? "true" : "false"); + ImGui::BulletText("Hovered: %s", plot.Hovered ? "true" : "false"); + ImGui::BulletText("Held: %s", plot.Held ? "true" : "false"); + ImGui::BulletText("HeldEdgeIdx: %d", plot.HeldEdgeIdx); + ImGui::BulletText("HeldPlaneIdx: %d", plot.HeldPlaneIdx); + ImGui::BulletText("LegendLocation: %s", GetShortLegendLocationName(plot.Items.Legend.Location)); + ImGui::BulletText("LegendHovered: %s", plot.Items.Legend.Hovered ? "true" : "false"); + ImGui::BulletText("LegendHeld: %s", plot.Items.Legend.Held ? "true" : "false"); + ImGui::BulletText("RotationCond: 0x%08X", plot.RotationCond); + ImGui::BulletText("InitialRotation: [%.2f,%.2f,%.2f,%.2f]", plot.InitialRotation.x, plot.InitialRotation.y, plot.InitialRotation.z, + plot.InitialRotation.w); + ImGui::BulletText("Rotation: [%.2f,%.2f,%.2f,%.2f]", plot.Rotation.x, plot.Rotation.y, plot.Rotation.z, plot.Rotation.w); + ImGui::BulletText("Animation: Time=%.4f RotationEnd=[%.2f,%.2f,%.2f,%.2f]", plot.AnimationTime, plot.RotationAnimationEnd.x, + plot.RotationAnimationEnd.y, plot.Rotation.z, plot.RotationAnimationEnd.w); + ImGui::BulletText("BoxScale: [%.2f,%.2f,%.2f]", plot.BoxScale.x, plot.BoxScale.y, plot.BoxScale.z); + ImGui::BulletText("BoxZoom: %.2f", plot.GetBoxZoom()); + + ImGui::TreePop(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Colormaps")) { + ImGui::BulletText("Colormaps: %d", gp.ColormapData.Count); + ImGui::BulletText("Memory: %d bytes", gp.ColormapData.Tables.Size * (int)(sizeof(gp.ColormapData.Tables.Data[0]))); + if (ImGui::TreeNode("Data")) { + for (int m = 0; m < gp.ColormapData.Count; ++m) { + if (ImGui::TreeNode(gp.ColormapData.GetName(m))) { + int count = gp.ColormapData.GetKeyCount(m); + int size = gp.ColormapData.GetTableSize(m); + bool qual = gp.ColormapData.IsQual(m); + ImGui::BulletText("Qualitative: %s", qual ? "true" : "false"); + ImGui::BulletText("Key Count: %d", count); + ImGui::BulletText("Table Size: %d", size); + ImGui::Indent(); + + static float t = 0.5; + ImVec4 samp; + float wid = 32 * 10 - ImGui::GetFrameHeight() - ImGui::GetStyle().ItemSpacing.x; + ImGui::SetNextItemWidth(wid); + ColormapSlider("##Sample", &t, &samp, "%.3f", m); + ImGui::SameLine(); + ImGui::ColorButton("Sampler", samp); + ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0, 0, 0, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + for (int c = 0; c < size; ++c) { + ImVec4 col = ImGui::ColorConvertU32ToFloat4(gp.ColormapData.GetTableColor(m, c)); + ImGui::PushID(m * 1000 + c); + ImGui::ColorButton("", col, 0, ImVec2(10, 10)); + ImGui::PopID(); + if ((c + 1) % 32 != 0 && c != size - 1) + ImGui::SameLine(); + } + ImGui::PopStyleVar(); + ImGui::PopStyleColor(); + ImGui::Unindent(); + ImGui::TreePop(); + } + } + ImGui::TreePop(); + } + ImGui::TreePop(); + } + ImGui::End(); +} + #endif // #ifndef IMGUI_DISABLE diff --git a/lib/third_party/imgui/implot3d/source/implot3d_demo.cpp b/lib/third_party/imgui/implot3d/source/implot3d_demo.cpp index 397816bad..4e47fe35c 100644 --- a/lib/third_party/imgui/implot3d/source/implot3d_demo.cpp +++ b/lib/third_party/imgui/implot3d/source/implot3d_demo.cpp @@ -1,5 +1,5 @@ //-------------------------------------------------- -// ImPlot3D v0.1 +// ImPlot3D v0.3 WIP // implot3d_demo.cpp // Date: 2024-11-17 // Author: Breno Cunha Queiroz (brenocq.com) @@ -47,6 +47,8 @@ namespace ImPlot3D { // [SECTION] Helpers //----------------------------------------------------------------------------- +#define CHECKBOX_FLAG(flags, flag) ImGui::CheckboxFlags(#flag, (unsigned int*)&flags, flag) + static void HelpMarker(const char* desc) { ImGui::TextDisabled("(?)"); if (ImGui::BeginItemTooltip()) { @@ -196,6 +198,12 @@ void DemoTrianglePlots() { // Now we have 18 vertices in xs, ys, zs forming the pyramid + // Triangle flags + static ImPlot3DTriangleFlags flags = ImPlot3DTriangleFlags_None; + CHECKBOX_FLAG(flags, ImPlot3DTriangleFlags_NoLines); + CHECKBOX_FLAG(flags, ImPlot3DTriangleFlags_NoFill); + CHECKBOX_FLAG(flags, ImPlot3DTriangleFlags_NoMarkers); + if (ImPlot3D::BeginPlot("Triangle Plots")) { ImPlot3D::SetupAxesLimits(-1, 1, -1, 1, -0.5, 1.5); @@ -205,7 +213,7 @@ void DemoTrianglePlots() { ImPlot3D::SetNextMarkerStyle(ImPlot3DMarker_Square, 3, ImPlot3D::GetColormapColor(2), IMPLOT3D_AUTO, ImPlot3D::GetColormapColor(2)); // Plot pyramid - ImPlot3D::PlotTriangle("Pyramid", xs, ys, zs, 6 * 3); // 6 triangles, 3 vertices each = 18 + ImPlot3D::PlotTriangle("Pyramid", xs, ys, zs, 6 * 3, flags); // 6 triangles, 3 vertices each = 18 ImPlot3D::EndPlot(); } } @@ -254,6 +262,12 @@ void DemoQuadPlots() { xs[23] = -1; ys[23] = 1; zs[23] = -1; // clang-format on + // Quad flags + static ImPlot3DQuadFlags flags = ImPlot3DQuadFlags_None; + CHECKBOX_FLAG(flags, ImPlot3DQuadFlags_NoLines); + CHECKBOX_FLAG(flags, ImPlot3DQuadFlags_NoFill); + CHECKBOX_FLAG(flags, ImPlot3DQuadFlags_NoMarkers); + if (ImPlot3D::BeginPlot("Quad Plots")) { ImPlot3D::SetupAxesLimits(-1.5f, 1.5f, -1.5f, 1.5f, -1.5f, 1.5f); @@ -262,21 +276,21 @@ void DemoQuadPlots() { ImPlot3D::SetNextFillStyle(colorX); ImPlot3D::SetNextLineStyle(colorX, 2); ImPlot3D::SetNextMarkerStyle(ImPlot3DMarker_Square, 3, colorX, IMPLOT3D_AUTO, colorX); - ImPlot3D::PlotQuad("X", &xs[0], &ys[0], &zs[0], 8); + ImPlot3D::PlotQuad("X", &xs[0], &ys[0], &zs[0], 8, flags); // Render +y and -y faces static ImVec4 colorY(0.2f, 0.8f, 0.2f, 0.8f); // Green ImPlot3D::SetNextFillStyle(colorY); ImPlot3D::SetNextLineStyle(colorY, 2); ImPlot3D::SetNextMarkerStyle(ImPlot3DMarker_Square, 3, colorY, IMPLOT3D_AUTO, colorY); - ImPlot3D::PlotQuad("Y", &xs[8], &ys[8], &zs[8], 8); + ImPlot3D::PlotQuad("Y", &xs[8], &ys[8], &zs[8], 8, flags); // Render +z and -z faces static ImVec4 colorZ(0.2f, 0.2f, 0.8f, 0.8f); // Blue ImPlot3D::SetNextFillStyle(colorZ); ImPlot3D::SetNextLineStyle(colorZ, 2); ImPlot3D::SetNextMarkerStyle(ImPlot3DMarker_Square, 3, colorZ, IMPLOT3D_AUTO, colorZ); - ImPlot3D::PlotQuad("Z", &xs[16], &ys[16], &zs[16], 8); + ImPlot3D::PlotQuad("Z", &xs[16], &ys[16], &zs[16], 8, flags); ImPlot3D::EndPlot(); } @@ -307,8 +321,7 @@ void DemoSurfacePlots() { ImGui::Text("Fill color"); static int selected_fill = 1; // Colormap by default static ImVec4 solid_color = ImVec4(0.8f, 0.8f, 0.2f, 0.6f); - const char* colormaps[] = {"Viridis", "Plasma", "Hot", "Cool", "Pink", "Jet", - "Twilight", "RdBu", "BrBG", "PiYG", "Spectral", "Greys"}; + const char* colormaps[] = {"Viridis", "Plasma", "Hot", "Cool", "Pink", "Jet", "Twilight", "RdBu", "BrBG", "PiYG", "Spectral", "Greys"}; static int sel_colormap = 5; // Jet by default { ImGui::Indent(); @@ -347,22 +360,34 @@ void DemoSurfacePlots() { ImGui::Unindent(); } + // Select flags + static ImPlot3DSurfaceFlags flags = ImPlot3DSurfaceFlags_NoMarkers; + CHECKBOX_FLAG(flags, ImPlot3DSurfaceFlags_NoLines); + CHECKBOX_FLAG(flags, ImPlot3DSurfaceFlags_NoFill); + CHECKBOX_FLAG(flags, ImPlot3DSurfaceFlags_NoMarkers); + // Begin the plot if (selected_fill == 1) ImPlot3D::PushColormap(colormaps[sel_colormap]); if (ImPlot3D::BeginPlot("Surface Plots", ImVec2(-1, 400), ImPlot3DFlags_NoClip)) { - // Set styles ImPlot3D::SetupAxesLimits(-1, 1, -1, 1, -1.5, 1.5); + + // Set fill style ImPlot3D::PushStyleVar(ImPlot3DStyleVar_FillAlpha, 0.8f); if (selected_fill == 0) ImPlot3D::SetNextFillStyle(solid_color); + + // Set line style ImPlot3D::SetNextLineStyle(ImPlot3D::GetColormapColor(1)); + // Set marker style + ImPlot3D::SetNextMarkerStyle(ImPlot3DMarker_Square, IMPLOT3D_AUTO, ImPlot3D::GetColormapColor(2)); + // Plot the surface if (custom_range) - ImPlot3D::PlotSurface("Wave Surface", xs, ys, zs, N, N, (double)range_min, (double)range_max); + ImPlot3D::PlotSurface("Wave Surface", xs, ys, zs, N, N, (double)range_min, (double)range_max, flags); else - ImPlot3D::PlotSurface("Wave Surface", xs, ys, zs, N, N); + ImPlot3D::PlotSurface("Wave Surface", xs, ys, zs, N, N, 0.0, 0.0, flags); // End the plot ImPlot3D::PopStyleVar(); @@ -376,55 +401,112 @@ void DemoMeshPlots() { static int mesh_id = 0; ImGui::Combo("Mesh", &mesh_id, "Duck\0Sphere\0Cube\0\0"); - // Choose fill color - static bool set_fill_color = true; - static ImVec4 fill_color = ImVec4(0.8f, 0.8f, 0.2f, 0.6f); - ImGui::Checkbox("Fill Color", &set_fill_color); - if (set_fill_color) { - ImGui::SameLine(); - ImGui::ColorEdit4("##MeshFillColor", (float*)&fill_color); - } - // Choose line color - static bool set_line_color = true; - static ImVec4 line_color = ImVec4(0.2f, 0.2f, 0.2f, 0.8f); - ImGui::Checkbox("Line Color", &set_line_color); - if (set_line_color) { - ImGui::SameLine(); - ImGui::ColorEdit4("##MeshLineColor", (float*)&line_color); - } + static ImVec4 line_color = ImVec4(0.5f, 0.5f, 0.2f, 0.6f); + ImGui::ColorEdit4("Line Color##Mesh", (float*)&line_color); + + // Choose fill color + static ImVec4 fill_color = ImVec4(0.8f, 0.8f, 0.2f, 0.6f); + ImGui::ColorEdit4("Fill Color##Mesh", (float*)&fill_color); // Choose marker color - static bool set_marker_color = false; - static ImVec4 marker_color = ImVec4(0.2f, 0.2f, 0.2f, 0.8f); - ImGui::Checkbox("Marker Color", &set_marker_color); - if (set_marker_color) { - ImGui::SameLine(); - ImGui::ColorEdit4("##MeshMarkerColor", (float*)&marker_color); - } + static ImVec4 marker_color = ImVec4(0.5f, 0.5f, 0.2f, 0.6f); + ImGui::ColorEdit4("Marker Color##Mesh", (float*)&marker_color); + + // Mesh flags + static ImPlot3DMeshFlags flags = ImPlot3DMeshFlags_NoMarkers; + CHECKBOX_FLAG(flags, ImPlot3DMeshFlags_NoLines); + CHECKBOX_FLAG(flags, ImPlot3DMeshFlags_NoFill); + CHECKBOX_FLAG(flags, ImPlot3DMeshFlags_NoMarkers); if (ImPlot3D::BeginPlot("Mesh Plots")) { ImPlot3D::SetupAxesLimits(-1, 1, -1, 1, -1, 1); - // Set colors - if (set_fill_color) - ImPlot3D::SetNextFillStyle(fill_color); - else { - // If not set as transparent, the fill color will be determined by the colormap - ImPlot3D::SetNextFillStyle(ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); - } - if (set_line_color) - ImPlot3D::SetNextLineStyle(line_color); - if (set_marker_color) - ImPlot3D::SetNextMarkerStyle(ImPlot3DMarker_Square, 3, marker_color, IMPLOT3D_AUTO, marker_color); + // Set fill style + ImPlot3D::SetNextFillStyle(fill_color); + + // Set line style + ImPlot3D::SetNextLineStyle(line_color); + + // Set marker style + ImPlot3D::SetNextMarkerStyle(ImPlot3DMarker_Square, 3, marker_color, IMPLOT3D_AUTO, marker_color); // Plot mesh if (mesh_id == 0) - ImPlot3D::PlotMesh("Duck", duck_vtx, duck_idx, DUCK_VTX_COUNT, DUCK_IDX_COUNT); + ImPlot3D::PlotMesh("Duck", duck_vtx, duck_idx, DUCK_VTX_COUNT, DUCK_IDX_COUNT, flags); else if (mesh_id == 1) - ImPlot3D::PlotMesh("Sphere", sphere_vtx, sphere_idx, SPHERE_VTX_COUNT, SPHERE_IDX_COUNT); + ImPlot3D::PlotMesh("Sphere", sphere_vtx, sphere_idx, SPHERE_VTX_COUNT, SPHERE_IDX_COUNT, flags); else if (mesh_id == 2) - ImPlot3D::PlotMesh("Cube", cube_vtx, cube_idx, CUBE_VTX_COUNT, CUBE_IDX_COUNT); + ImPlot3D::PlotMesh("Cube", cube_vtx, cube_idx, CUBE_VTX_COUNT, CUBE_IDX_COUNT, flags); + + ImPlot3D::EndPlot(); + } +} + +void DemoImagePlots() { + ImGui::BulletText("Below we are displaying the font texture, which is the only texture we have\naccess to in this demo."); + ImGui::BulletText("Use the 'ImTextureID' type as storage to pass pointers or identifiers to your\nown texture data."); + ImGui::BulletText("See ImGui Wiki page 'Image Loading and Displaying Examples'."); + + static ImVec4 tint1(1, 1, 1, 1); + static ImVec4 tint2(1, 1, 1, 1); + + static ImPlot3DPoint center1(0, 0, 1); + static ImPlot3DPoint axis_u1(1, 0, 0); + static ImPlot3DPoint axis_v1(0, 1, 0); + static ImVec2 uv0_1(0, 0), uv1_1(1, 1); + + static ImPlot3DPoint p0(-1, -1, 0); + static ImPlot3DPoint p1(1, -1, 0); + static ImPlot3DPoint p2(1, 1, 0); + static ImPlot3DPoint p3(-1, 1, 0); + static ImVec2 uv0(0, 0), uv1(1, 0), uv2(1, 1), uv3(0, 1); + + // Spacing + ImGui::Dummy(ImVec2(0, 10)); + + // Image 1 Controls + if (ImGui::TreeNodeEx("Image 1 Controls: Center + Axes")) { + ImGui::SliderFloat3("Center", ¢er1.x, -2, 2, "%.1f"); + ImGui::SliderFloat3("Axis U", &axis_u1.x, -2, 2, "%.1f"); + ImGui::SliderFloat3("Axis V", &axis_v1.x, -2, 2, "%.1f"); + ImGui::SliderFloat2("UV0", &uv0_1.x, 0, 1, "%.2f"); + ImGui::SliderFloat2("UV1", &uv1_1.x, 0, 1, "%.2f"); + ImGui::ColorEdit4("Tint", &tint1.x); + + ImGui::TreePop(); + } + + // Image 2 Controls + if (ImGui::TreeNodeEx("Image 2 Controls: Full Quad")) { + ImGui::SliderFloat3("P0", &p0.x, -2, 2, "%.1f"); + ImGui::SliderFloat3("P1", &p1.x, -2, 2, "%.1f"); + ImGui::SliderFloat3("P2", &p2.x, -2, 2, "%.1f"); + ImGui::SliderFloat3("P3", &p3.x, -2, 2, "%.1f"); + + ImGui::SliderFloat2("UV0", &uv0.x, 0, 1, "%.2f"); + ImGui::SliderFloat2("UV1", &uv1.x, 0, 1, "%.2f"); + ImGui::SliderFloat2("UV2", &uv2.x, 0, 1, "%.2f"); + ImGui::SliderFloat2("UV3", &uv3.x, 0, 1, "%.2f"); + + ImGui::ColorEdit4("Tint##2", &tint2.x); + + ImGui::TreePop(); + } + + // Plot + if (ImPlot3D::BeginPlot("Image Plot", ImVec2(-1, 0), ImPlot3DFlags_NoClip)) { +#ifdef IMGUI_HAS_TEXTURES + // We use the font atlas ImTextureRef for this demo, but in your real code when you submit + // an image that you have loaded yourself, you would normally have a ImTextureID which works + // just as well (as ImTextureRef can be constructed from ImTextureID). + ImTextureRef tex = ImGui::GetIO().Fonts->TexRef; +#else + ImTextureID tex = ImGui::GetIO().Fonts->TexID; +#endif + + ImPlot3D::PlotImage("Image 1", tex, center1, axis_u1, axis_v1, uv0_1, uv1_1, tint1); + ImPlot3D::PlotImage("Image 2", tex, p0, p1, p2, p3, uv0, uv1, uv2, uv3, tint2); ImPlot3D::EndPlot(); } @@ -470,7 +552,8 @@ void DemoMarkersAndText() { if (ImPlot3D::BeginPlot("##MarkerStyles", ImVec2(-1, 0), ImPlot3DFlags_CanvasOnly)) { - ImPlot3D::SetupAxes(nullptr, nullptr, nullptr, ImPlot3DAxisFlags_NoDecorations, ImPlot3DAxisFlags_NoDecorations, ImPlot3DAxisFlags_NoDecorations); + ImPlot3D::SetupAxes(nullptr, nullptr, nullptr, ImPlot3DAxisFlags_NoDecorations, ImPlot3DAxisFlags_NoDecorations, + ImPlot3DAxisFlags_NoDecorations); ImPlot3D::SetupAxesLimits(-0.5, 1.5, -0.5, 1.5, 0, ImPlot3DMarker_COUNT + 1); float xs[2] = {0, 0}; @@ -565,8 +648,54 @@ void DemoBoxScale() { } } +void DemoBoxRotation() { + float origin[2] = {0.0f, 0.0f}; + float axis[2] = {0.0f, 1.0f}; + + // Sliders for rotation angles + static float elevation = 45.0f; + static float azimuth = -135.0f; + static bool animate = false; + ImGui::Text("Rotation"); + bool changed = false; + if (ImGui::SliderFloat("Elevation", &elevation, -90.0f, 90.0f, "%.1f degrees")) + changed = true; + if (ImGui::SliderFloat("Azimuth", &azimuth, -180.0f, 180.0f, "%.1f degrees")) + changed = true; + ImGui::Checkbox("Animate", &animate); + + ImGui::Text("Initial Rotation"); + ImGui::SameLine(); + HelpMarker("The rotation will be reset to the initial rotation when you double right-click"); + static float init_elevation = 45.0f; + static float init_azimuth = -135.0f; + ImGui::SliderFloat("Initial Elevation", &init_elevation, -90.0f, 90.0f, "%.1f degrees"); + ImGui::SliderFloat("Initial Azimuth", &init_azimuth, -180.0f, 180.0f, "%.1f degrees"); + + if (ImPlot3D::BeginPlot("##BoxRotation")) { + ImPlot3D::SetupAxesLimits(-1, 1, -1, 1, -1, 1, ImPlot3DCond_Always); + + // Set initial rotation + ImPlot3D::SetupBoxInitialRotation(init_elevation, init_azimuth); + + // Set the rotation using the specified elevation and azimuth + if (changed) + ImPlot3D::SetupBoxRotation(elevation, azimuth, animate, ImPlot3DCond_Always); + + // Plot axis lines + ImPlot3D::SetNextLineStyle(ImVec4(0.8f, 0.2f, 0.2f, 1)); + ImPlot3D::PlotLine("X-Axis", axis, origin, origin, 2); + ImPlot3D::SetNextLineStyle(ImVec4(0.2f, 0.8f, 0.2f, 1)); + ImPlot3D::PlotLine("Y-Axis", origin, axis, origin, 2); + ImPlot3D::SetNextLineStyle(ImVec4(0.2f, 0.2f, 0.8f, 1)); + ImPlot3D::PlotLine("Z-Axis", origin, origin, axis, 2); + + ImPlot3D::EndPlot(); + } +} + void DemoTickLabels() { - static bool custom_ticks = false; + static bool custom_ticks = true; static bool custom_labels = true; ImGui::Checkbox("Show Custom Ticks", &custom_ticks); if (custom_ticks) { @@ -588,6 +717,26 @@ void DemoTickLabels() { } } +void DemoAxisConstraints() { + static float limit_constraints[2] = {-10, 10}; + static float zoom_constraints[2] = {1, 20}; + static ImPlot3DAxisFlags flags; + ImGui::DragFloat2("Limits Constraints", limit_constraints, 0.01f); + ImGui::DragFloat2("Zoom Constraints", zoom_constraints, 0.01f); + CHECKBOX_FLAG(flags, ImPlot3DAxisFlags_PanStretch); + if (ImPlot3D::BeginPlot("##AxisConstraints", ImVec2(-1, 0))) { + ImPlot3D::SetupAxes("X", "Y", "Z", flags, flags, flags); + ImPlot3D::SetupAxesLimits(-1, 1, -1, 1, -1, 1); + ImPlot3D::SetupAxisLimitsConstraints(ImAxis3D_X, limit_constraints[0], limit_constraints[1]); + ImPlot3D::SetupAxisLimitsConstraints(ImAxis3D_Y, limit_constraints[0], limit_constraints[1]); + ImPlot3D::SetupAxisLimitsConstraints(ImAxis3D_Z, limit_constraints[0], limit_constraints[1]); + ImPlot3D::SetupAxisZoomConstraints(ImAxis3D_X, zoom_constraints[0], zoom_constraints[1]); + ImPlot3D::SetupAxisZoomConstraints(ImAxis3D_Y, zoom_constraints[0], zoom_constraints[1]); + ImPlot3D::SetupAxisZoomConstraints(ImAxis3D_Z, zoom_constraints[0], zoom_constraints[1]); + ImPlot3D::EndPlot(); + } +} + //----------------------------------------------------------------------------- // [SECTION] Custom //----------------------------------------------------------------------------- @@ -624,14 +773,8 @@ void DemoCustomRendering() { // Draw box ImPlot3DPoint corners[8] = { - ImPlot3DPoint(0, 0, 0), - ImPlot3DPoint(1, 0, 0), - ImPlot3DPoint(1, 1, 0), - ImPlot3DPoint(0, 1, 0), - ImPlot3DPoint(0, 0, 1), - ImPlot3DPoint(1, 0, 1), - ImPlot3DPoint(1, 1, 1), - ImPlot3DPoint(0, 1, 1), + ImPlot3DPoint(0, 0, 0), ImPlot3DPoint(1, 0, 0), ImPlot3DPoint(1, 1, 0), ImPlot3DPoint(0, 1, 0), + ImPlot3DPoint(0, 0, 1), ImPlot3DPoint(1, 0, 1), ImPlot3DPoint(1, 1, 1), ImPlot3DPoint(0, 1, 1), }; ImVec2 corners_px[8]; for (int i = 0; i < 8; i++) @@ -720,18 +863,57 @@ void DemoHeader(const char* label, void (*demo)()) { } } +void ShowAllDemos() { + ImGui::Text("ImPlot3D says olá! (%s)", IMPLOT3D_VERSION); + ImGui::Spacing(); + if (ImGui::BeginTabBar("ImPlot3DDemoTabs")) { + if (ImGui::BeginTabItem("Plots")) { + DemoHeader("Line Plots", DemoLinePlots); + DemoHeader("Scatter Plots", DemoScatterPlots); + DemoHeader("Triangle Plots", DemoTrianglePlots); + DemoHeader("Quad Plots", DemoQuadPlots); + DemoHeader("Surface Plots", DemoSurfacePlots); + DemoHeader("Mesh Plots", DemoMeshPlots); + DemoHeader("Realtime Plots", DemoRealtimePlots); + DemoHeader("Image Plots", DemoImagePlots); + DemoHeader("Markers and Text", DemoMarkersAndText); + DemoHeader("NaN Values", DemoNaNValues); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Axes")) { + DemoHeader("Box Scale", DemoBoxScale); + DemoHeader("Box Rotation", DemoBoxRotation); + DemoHeader("Tick Labels", DemoTickLabels); + DemoHeader("Axis Constraints", DemoAxisConstraints); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Custom")) { + DemoHeader("Custom Styles", DemoCustomStyles); + DemoHeader("Custom Rendering", DemoCustomRendering); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Help")) { + DemoHelp(); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } +} + void ShowDemoWindow(bool* p_open) { + static bool show_implot3d_metrics = false; static bool show_implot3d_style_editor = false; static bool show_imgui_metrics = false; static bool show_imgui_style_editor = false; static bool show_imgui_demo = false; + if (show_implot3d_metrics) + ImPlot3D::ShowMetricsWindow(&show_implot3d_metrics); if (show_implot3d_style_editor) { ImGui::Begin("Style Editor (ImPlot3D)", &show_implot3d_style_editor); ImPlot3D::ShowStyleEditor(); ImGui::End(); } - if (show_imgui_style_editor) { ImGui::Begin("Style Editor (ImGui)", &show_imgui_style_editor); ImGui::ShowStyleEditor(); @@ -747,6 +929,7 @@ void ShowDemoWindow(bool* p_open) { ImGui::Begin("ImPlot3D Demo", p_open, ImGuiWindowFlags_MenuBar); if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("Tools")) { + ImGui::MenuItem("Metrics", nullptr, &show_implot3d_metrics); ImGui::MenuItem("Style Editor", nullptr, &show_implot3d_style_editor); ImGui::Separator(); ImGui::MenuItem("ImGui Metrics", nullptr, &show_imgui_metrics); @@ -756,40 +939,7 @@ void ShowDemoWindow(bool* p_open) { } ImGui::EndMenuBar(); } - - ImGui::Text("ImPlot3D says olá! (%s)", IMPLOT3D_VERSION); - - ImGui::Spacing(); - - if (ImGui::BeginTabBar("ImPlot3DDemoTabs")) { - if (ImGui::BeginTabItem("Plots")) { - DemoHeader("Line Plots", DemoLinePlots); - DemoHeader("Scatter Plots", DemoScatterPlots); - DemoHeader("Triangle Plots", DemoTrianglePlots); - DemoHeader("Quad Plots", DemoQuadPlots); - DemoHeader("Surface Plots", DemoSurfacePlots); - DemoHeader("Mesh Plots", DemoMeshPlots); - DemoHeader("Realtime Plots", DemoRealtimePlots); - DemoHeader("Markers and Text", DemoMarkersAndText); - DemoHeader("NaN Values", DemoNaNValues); - ImGui::EndTabItem(); - } - if (ImGui::BeginTabItem("Axes")) { - DemoHeader("Box Scale", DemoBoxScale); - DemoHeader("Tick Labels", DemoTickLabels); - ImGui::EndTabItem(); - } - if (ImGui::BeginTabItem("Custom")) { - DemoHeader("Custom Styles", DemoCustomStyles); - DemoHeader("Custom Rendering", DemoCustomRendering); - ImGui::EndTabItem(); - } - if (ImGui::BeginTabItem("Help")) { - DemoHelp(); - ImGui::EndTabItem(); - } - ImGui::EndTabBar(); - } + ShowAllDemos(); ImGui::End(); } @@ -811,43 +961,6 @@ bool ShowStyleSelector(const char* label) { return false; } -void RenderColorBar(const ImU32* colors, int size, ImDrawList& DrawList, const ImRect& bounds, bool vert, bool reversed, bool continuous) { - const int n = continuous ? size - 1 : size; - ImU32 col1, col2; - if (vert) { - const float step = bounds.GetHeight() / n; - ImRect rect(bounds.Min.x, bounds.Min.y, bounds.Max.x, bounds.Min.y + step); - for (int i = 0; i < n; ++i) { - if (reversed) { - col1 = colors[size - i - 1]; - col2 = continuous ? colors[size - i - 2] : col1; - } else { - col1 = colors[i]; - col2 = continuous ? colors[i + 1] : col1; - } - DrawList.AddRectFilledMultiColor(rect.Min, rect.Max, col1, col1, col2, col2); - rect.TranslateY(step); - } - } else { - const float step = bounds.GetWidth() / n; - ImRect rect(bounds.Min.x, bounds.Min.y, bounds.Min.x + step, bounds.Max.y); - for (int i = 0; i < n; ++i) { - if (reversed) { - col1 = colors[size - i - 1]; - col2 = continuous ? colors[size - i - 2] : col1; - } else { - col1 = colors[i]; - col2 = continuous ? colors[i + 1] : col1; - } - DrawList.AddRectFilledMultiColor(rect.Min, rect.Max, col1, col2, col2, col1); - rect.TranslateX(step); - } - } -} - -static inline ImU32 CalcTextColor(const ImVec4& bg) { return (bg.x * 0.299f + bg.y * 0.587f + bg.z * 0.114f) > 0.5f ? IM_COL32_BLACK : IM_COL32_WHITE; } -static inline ImU32 CalcTextColor(ImU32 bg) { return CalcTextColor(ImGui::ColorConvertU32ToFloat4(bg)); } - bool ColormapButton(const char* label, const ImVec2& size_arg, ImPlot3DColormap cmap) { ImGuiContext& G = *GImGui; const ImGuiStyle& style = G.Style; @@ -920,9 +1033,8 @@ void ShowStyleEditor(ImPlot3DStyle* ref) { if (ImGui::Button("Revert Ref")) style = *ref; ImGui::SameLine(); - HelpMarker( - "Save/Revert in local non-persistent storage. Default Colors definition are not affected. " - "Use \"Export\" below to save them somewhere."); + HelpMarker("Save/Revert in local non-persistent storage. Default Colors definition are not affected. " + "Use \"Export\" below to save them somewhere."); ImGui::Separator(); @@ -958,8 +1070,8 @@ void ShowStyleEditor(ImPlot3DStyle* ref) { const ImVec4& col = style.Colors[i]; const char* name = ImPlot3D::GetStyleColorName(i); if (!output_only_modified || memcmp(&col, &ref->Colors[i], sizeof(ImVec4)) != 0) - ImGui::LogText("colors[ImPlot3DCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);\n", - name, 15 - (int)strlen(name), "", col.x, col.y, col.z, col.w); + ImGui::LogText("colors[ImPlot3DCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);\n", name, 15 - (int)strlen(name), "", col.x, + col.y, col.z, col.w); } ImGui::LogFinish(); } @@ -973,6 +1085,17 @@ void ShowStyleEditor(ImPlot3DStyle* ref) { filter.Draw("Filter colors", ImGui::GetFontSize() * 16); static ImGuiColorEditFlags alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; +#if IMGUI_VERSION_NUM < 19173 + if (ImGui::RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_None)) + alpha_flags = ImGuiColorEditFlags_None; + ImGui::SameLine(); + if (ImGui::RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_AlphaPreview)) + alpha_flags = ImGuiColorEditFlags_AlphaPreview; + ImGui::SameLine(); + if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) + alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; + ImGui::SameLine(); +#else if (ImGui::RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_AlphaOpaque)) alpha_flags = ImGuiColorEditFlags_AlphaOpaque; ImGui::SameLine(); @@ -982,10 +1105,10 @@ void ShowStyleEditor(ImPlot3DStyle* ref) { if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; ImGui::SameLine(); - HelpMarker( - "In the color list:\n" - "Left-click on color square to open color picker,\n" - "Right-click to open edit options menu."); +#endif + HelpMarker("In the color list:\n" + "Left-click on color square to open color picker,\n" + "Right-click to open edit options menu."); ImGui::Separator(); diff --git a/lib/third_party/imgui/implot3d/source/implot3d_items.cpp b/lib/third_party/imgui/implot3d/source/implot3d_items.cpp index e8afd5496..703044ade 100644 --- a/lib/third_party/imgui/implot3d/source/implot3d_items.cpp +++ b/lib/third_party/imgui/implot3d/source/implot3d_items.cpp @@ -1,5 +1,5 @@ //-------------------------------------------------- -// ImPlot3D v0.1 +// ImPlot3D v0.3 WIP // implot3d_items.cpp // Date: 2024-11-26 // Author: Breno Cunha Queiroz (brenocq.com) @@ -25,6 +25,10 @@ // [SECTION] PlotScatter // [SECTION] PlotLine // [SECTION] PlotTriangle +// [SECTION] PlotQuad +// [SECTION] PlotSurface +// [SECTION] PlotMesh +// [SECTION] PlotImage // [SECTION] PlotText //----------------------------------------------------------------------------- @@ -67,14 +71,14 @@ #endif // clang-format on -#define IMPLOT3D_NORMALIZE2F(VX, VY) \ - do { \ - float d2 = VX * VX + VY * VY; \ - if (d2 > 0.0f) { \ - float inv_len = ImRsqrt(d2); \ - VX *= inv_len; \ - VY *= inv_len; \ - } \ +#define IMPLOT3D_NORMALIZE2F(VX, VY) \ + do { \ + float d2 = VX * VX + VY * VY; \ + if (d2 > 0.0f) { \ + float inv_len = ImRsqrt(d2); \ + VX *= inv_len; \ + VY *= inv_len; \ + } \ } while (0) IMPLOT3D_INLINE void GetLineRenderProps(const ImDrawList3D& draw_list_3d, float& half_weight, ImVec2& tex_uv0, ImVec2& tex_uv1) { @@ -109,7 +113,8 @@ IMPLOT3D_INLINE void GetLineRenderProps(const ImDrawList3D& draw_list_3d, float& // As an example, you could use the compile time define given by the line below in order to support only float and double. // -DIMPLOT3D_CUSTOM_NUMERIC_TYPES="(float)(double)" // In order to support all known C++ types, use: -// -DIMPLOT3D_CUSTOM_NUMERIC_TYPES="(signed char)(unsigned char)(signed short)(unsigned short)(signed int)(unsigned int)(signed long)(unsigned long)(signed long long)(unsigned long long)(float)(double)(long double)" +// -DIMPLOT3D_CUSTOM_NUMERIC_TYPES="(signed char)(unsigned char)(signed short)(unsigned short)(signed int)(unsigned int)(signed long)(unsigned +// long)(signed long long)(unsigned long long)(float)(double)(long double)" #ifdef IMPLOT3D_CUSTOM_NUMERIC_TYPES #define IMPLOT3D_NUMERIC_TYPES IMPLOT3D_CUSTOM_NUMERIC_TYPES @@ -148,6 +153,8 @@ bool BeginItem(const char* label_id, ImPlot3DItemFlags flags, ImPlot3DCol recolo // Register item bool just_created; ImPlot3DItem* item = RegisterOrGetItem(label_id, flags, &just_created); + // Set current item + gp.CurrentItem = item; // Set/override item color if (recolor_from != -1) { @@ -165,10 +172,20 @@ bool BeginItem(const char* label_id, ImPlot3DItemFlags flags, ImPlot3DCol recolo ImVec4 item_color = ImGui::ColorConvertU32ToFloat4(item->Color); n.IsAutoLine = IsColorAuto(n.Colors[ImPlot3DCol_Line]) && IsColorAuto(ImPlot3DCol_Line); n.IsAutoFill = IsColorAuto(n.Colors[ImPlot3DCol_Fill]) && IsColorAuto(ImPlot3DCol_Fill); - n.Colors[ImPlot3DCol_Line] = IsColorAuto(n.Colors[ImPlot3DCol_Line]) ? (IsColorAuto(ImPlot3DCol_Line) ? item_color : gp.Style.Colors[ImPlot3DCol_Line]) : n.Colors[ImPlot3DCol_Line]; - n.Colors[ImPlot3DCol_Fill] = IsColorAuto(n.Colors[ImPlot3DCol_Fill]) ? (IsColorAuto(ImPlot3DCol_Fill) ? item_color : gp.Style.Colors[ImPlot3DCol_Fill]) : n.Colors[ImPlot3DCol_Fill]; - n.Colors[ImPlot3DCol_MarkerOutline] = IsColorAuto(n.Colors[ImPlot3DCol_MarkerOutline]) ? (IsColorAuto(ImPlot3DCol_MarkerOutline) ? n.Colors[ImPlot3DCol_Line] : gp.Style.Colors[ImPlot3DCol_MarkerOutline]) : n.Colors[ImPlot3DCol_MarkerOutline]; - n.Colors[ImPlot3DCol_MarkerFill] = IsColorAuto(n.Colors[ImPlot3DCol_MarkerFill]) ? (IsColorAuto(ImPlot3DCol_MarkerFill) ? n.Colors[ImPlot3DCol_Line] : gp.Style.Colors[ImPlot3DCol_MarkerFill]) : n.Colors[ImPlot3DCol_MarkerFill]; + n.Colors[ImPlot3DCol_Line] = IsColorAuto(n.Colors[ImPlot3DCol_Line]) + ? (IsColorAuto(ImPlot3DCol_Line) ? item_color : gp.Style.Colors[ImPlot3DCol_Line]) + : n.Colors[ImPlot3DCol_Line]; + n.Colors[ImPlot3DCol_Fill] = IsColorAuto(n.Colors[ImPlot3DCol_Fill]) + ? (IsColorAuto(ImPlot3DCol_Fill) ? item_color : gp.Style.Colors[ImPlot3DCol_Fill]) + : n.Colors[ImPlot3DCol_Fill]; + n.Colors[ImPlot3DCol_MarkerOutline] = + IsColorAuto(n.Colors[ImPlot3DCol_MarkerOutline]) + ? (IsColorAuto(ImPlot3DCol_MarkerOutline) ? n.Colors[ImPlot3DCol_Line] : gp.Style.Colors[ImPlot3DCol_MarkerOutline]) + : n.Colors[ImPlot3DCol_MarkerOutline]; + n.Colors[ImPlot3DCol_MarkerFill] = + IsColorAuto(n.Colors[ImPlot3DCol_MarkerFill]) + ? (IsColorAuto(ImPlot3DCol_MarkerFill) ? n.Colors[ImPlot3DCol_Line] : gp.Style.Colors[ImPlot3DCol_MarkerFill]) + : n.Colors[ImPlot3DCol_MarkerFill]; // Set size & weight n.LineWeight = n.LineWeight < 0.0f ? style.LineWeight : n.LineWeight; @@ -222,6 +239,7 @@ bool BeginItemEx(const char* label_id, const _Getter& getter, ImPlot3DItemFlags void EndItem() { ImPlot3DContext& gp = *GImPlot3D; gp.NextItemData.Reset(); + gp.CurrentItem = nullptr; } ImPlot3DItem* RegisterOrGetItem(const char* label_id, ImPlot3DItemFlags flags, bool* just_created) { @@ -248,6 +266,11 @@ ImPlot3DItem* RegisterOrGetItem(const char* label_id, ImPlot3DItemFlags flags, b return item; } +ImPlot3DItem* GetCurrentItem() { + ImPlot3DContext& gp = *GImPlot3D; + return gp.CurrentItem; +} + void BustItemCache() { ImPlot3DContext& gp = *GImPlot3D; for (int p = 0; p < gp.Plots.GetBufSize(); ++p) { @@ -284,7 +307,8 @@ void SetNextMarkerStyle(ImPlot3DMarker marker, float size, const ImVec4& fill, f // [SECTION] Draw Utils //----------------------------------------------------------------------------- -IMPLOT3D_INLINE void PrimLine(ImDrawList3D& draw_list_3d, const ImVec2& P1, const ImVec2& P2, float half_weight, ImU32 col, const ImVec2& tex_uv0, const ImVec2 tex_uv1, float z) { +IMPLOT3D_INLINE void PrimLine(ImDrawList3D& draw_list_3d, const ImVec2& P1, const ImVec2& P2, float half_weight, ImU32 col, const ImVec2& tex_uv0, + const ImVec2& tex_uv1, float z) { float dx = P2.x - P1.x; float dy = P2.y - P1.y; IMPLOT3D_NORMALIZE2F(dx, dy); @@ -327,30 +351,31 @@ IMPLOT3D_INLINE void PrimLine(ImDrawList3D& draw_list_3d, const ImVec2& P1, cons float GetPointDepth(ImPlot3DPoint p) { ImPlot3DContext& gp = *GImPlot3D; ImPlot3DPlot& plot = *gp.CurrentPlot; + + // Adjust for inverted axes before rotation + if (ImHasFlag(plot.Axes[0].Flags, ImPlot3DAxisFlags_Invert)) + p.x = -p.x; + if (ImHasFlag(plot.Axes[1].Flags, ImPlot3DAxisFlags_Invert)) + p.y = -p.y; + if (ImHasFlag(plot.Axes[2].Flags, ImPlot3DAxisFlags_Invert)) + p.z = -p.z; + ImPlot3DPoint p_rot = plot.Rotation * p; return p_rot.z; } struct RendererBase { - RendererBase(int prims, int idx_consumed, int vtx_consumed) : Prims(prims), - IdxConsumed(idx_consumed), - VtxConsumed(vtx_consumed) {} + RendererBase(int prims, int idx_consumed, int vtx_consumed) : Prims(prims), IdxConsumed(idx_consumed), VtxConsumed(vtx_consumed) {} const unsigned int Prims; // Number of primitives to render const unsigned int IdxConsumed; // Number of indices consumed per primitive const unsigned int VtxConsumed; // Number of vertices consumed per primitive }; -template -struct RendererMarkersFill : RendererBase { - RendererMarkersFill(const _Getter& getter, const ImVec2* marker, int count, float size, ImU32 col) : RendererBase(getter.Count, (count - 2) * 3, count), - Getter(getter), - Marker(marker), - Count(count), - Size(size), - Col(col) {} - void Init(ImDrawList3D& draw_list_3d) const { - UV = draw_list_3d._SharedData->TexUvWhitePixel; - } +template struct RendererMarkersFill : RendererBase { + RendererMarkersFill(const _Getter& getter, const ImVec2* marker, int count, float size, ImU32 col) + : RendererBase(getter.Count, (count - 2) * 3, count), Getter(getter), Marker(marker), Count(count), Size(size), Col(col) {} + + void Init(ImDrawList3D& draw_list_3d) const { UV = draw_list_3d._SharedData->TexUvWhitePixel; } IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { ImPlot3DPoint p_plot = Getter(prim); @@ -388,13 +413,12 @@ struct RendererMarkersFill : RendererBase { mutable ImVec2 UV; }; -template -struct RendererMarkersLine : RendererBase { - RendererMarkersLine(const _Getter& getter, const ImVec2* marker, int count, float size, float weight, ImU32 col) : RendererBase(getter.Count, count / 2 * 6, count / 2 * 4), Getter(getter), Marker(marker), Count(count), HalfWeight(ImMax(1.0f, weight) * 0.5f), Size(size), Col(col) {} +template struct RendererMarkersLine : RendererBase { + RendererMarkersLine(const _Getter& getter, const ImVec2* marker, int count, float size, float weight, ImU32 col) + : RendererBase(getter.Count, count / 2 * 6, count / 2 * 4), Getter(getter), Marker(marker), Count(count), + HalfWeight(ImMax(1.0f, weight) * 0.5f), Size(size), Col(col) {} - void Init(ImDrawList3D& draw_list_3d) const { - GetLineRenderProps(draw_list_3d, HalfWeight, UV0, UV1); - } + void Init(ImDrawList3D& draw_list_3d) const { GetLineRenderProps(draw_list_3d, HalfWeight, UV0, UV1); } IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { ImPlot3DPoint p_plot = Getter(prim); @@ -419,20 +443,14 @@ struct RendererMarkersLine : RendererBase { mutable ImVec2 UV1; }; -template -struct RendererLineStrip : RendererBase { +template struct RendererLineStrip : RendererBase { RendererLineStrip(const _Getter& getter, ImU32 col, float weight) - : RendererBase(getter.Count - 1, 6, 4), - Getter(getter), - Col(col), - HalfWeight(ImMax(1.0f, weight) * 0.5f) { + : RendererBase(getter.Count - 1, 6, 4), Getter(getter), Col(col), HalfWeight(ImMax(1.0f, weight) * 0.5f) { // Initialize the first point in plot coordinates P1_plot = Getter(0); } - void Init(ImDrawList3D& draw_list_3d) const { - GetLineRenderProps(draw_list_3d, HalfWeight, UV0, UV1); - } + void Init(ImDrawList3D& draw_list_3d) const { GetLineRenderProps(draw_list_3d, HalfWeight, UV0, UV1); } IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { ImPlot3DPoint P2_plot = Getter(prim + 1); @@ -463,20 +481,14 @@ struct RendererLineStrip : RendererBase { mutable ImVec2 UV1; }; -template -struct RendererLineStripSkip : RendererBase { +template struct RendererLineStripSkip : RendererBase { RendererLineStripSkip(const _Getter& getter, ImU32 col, float weight) - : RendererBase(getter.Count - 1, 6, 4), - Getter(getter), - Col(col), - HalfWeight(ImMax(1.0f, weight) * 0.5f) { + : RendererBase(getter.Count - 1, 6, 4), Getter(getter), Col(col), HalfWeight(ImMax(1.0f, weight) * 0.5f) { // Initialize the first point in plot coordinates P1_plot = Getter(0); } - void Init(ImDrawList3D& draw_list_3d) const { - GetLineRenderProps(draw_list_3d, HalfWeight, UV0, UV1); - } + void Init(ImDrawList3D& draw_list_3d) const { GetLineRenderProps(draw_list_3d, HalfWeight, UV0, UV1); } IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { // Get the next point in plot coordinates @@ -484,8 +496,7 @@ struct RendererLineStripSkip : RendererBase { bool visible = false; // Check for NaNs in P1_plot and P2_plot - if (!ImNan(P1_plot.x) && !ImNan(P1_plot.y) && !ImNan(P1_plot.z) && - !ImNan(P2_plot.x) && !ImNan(P2_plot.y) && !ImNan(P2_plot.z)) { + if (!ImNan(P1_plot.x) && !ImNan(P1_plot.y) && !ImNan(P1_plot.z) && !ImNan(P2_plot.x) && !ImNan(P2_plot.y) && !ImNan(P2_plot.z)) { // Clip the line segment to the culling box ImPlot3DPoint P1_clipped, P2_clipped; @@ -515,17 +526,11 @@ struct RendererLineStripSkip : RendererBase { mutable ImVec2 UV1; }; -template -struct RendererLineSegments : RendererBase { +template struct RendererLineSegments : RendererBase { RendererLineSegments(const _Getter& getter, ImU32 col, float weight) - : RendererBase(getter.Count / 2, 6, 4), - Getter(getter), - Col(col), - HalfWeight(ImMax(1.0f, weight) * 0.5f) {} + : RendererBase(getter.Count / 2, 6, 4), Getter(getter), Col(col), HalfWeight(ImMax(1.0f, weight) * 0.5f) {} - void Init(ImDrawList3D& draw_list_3d) const { - GetLineRenderProps(draw_list_3d, HalfWeight, UV0, UV1); - } + void Init(ImDrawList3D& draw_list_3d) const { GetLineRenderProps(draw_list_3d, HalfWeight, UV0, UV1); } IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { // Get the segment's endpoints in plot coordinates @@ -533,8 +538,7 @@ struct RendererLineSegments : RendererBase { ImPlot3DPoint P2_plot = Getter(prim * 2 + 1); // Check for NaNs in P1_plot and P2_plot - if (!ImNan(P1_plot.x) && !ImNan(P1_plot.y) && !ImNan(P1_plot.z) && - !ImNan(P2_plot.x) && !ImNan(P2_plot.y) && !ImNan(P2_plot.z)) { + if (!ImNan(P1_plot.x) && !ImNan(P1_plot.y) && !ImNan(P1_plot.z) && !ImNan(P2_plot.x) && !ImNan(P2_plot.y) && !ImNan(P2_plot.z)) { // Clip the line segment to the culling box ImPlot3DPoint P1_clipped, P2_clipped; @@ -560,14 +564,10 @@ struct RendererLineSegments : RendererBase { mutable ImVec2 UV1; }; -template -struct RendererTriangleFill : RendererBase { - RendererTriangleFill(const _Getter& getter, ImU32 col) : RendererBase(getter.Count / 3, 3, 3), - Getter(getter), - Col(col) {} - void Init(ImDrawList3D& draw_list_3d) const { - UV = draw_list_3d._SharedData->TexUvWhitePixel; - } +template struct RendererTriangleFill : RendererBase { + RendererTriangleFill(const _Getter& getter, ImU32 col) : RendererBase(getter.Count / 3, 3, 3), Getter(getter), Col(col) {} + + void Init(ImDrawList3D& draw_list_3d) const { UV = draw_list_3d._SharedData->TexUvWhitePixel; } IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { ImPlot3DPoint p_plot[3]; @@ -576,7 +576,7 @@ struct RendererTriangleFill : RendererBase { p_plot[2] = Getter(3 * prim + 2); // Check if the triangle is outside the culling box - if (!cull_box.Contains(p_plot[0]) && !cull_box.Contains(p_plot[0]) && !cull_box.Contains(p_plot[1])) + if (!cull_box.Contains(p_plot[0]) && !cull_box.Contains(p_plot[1]) && !cull_box.Contains(p_plot[2])) return false; // Project the triangle vertices to screen space @@ -620,14 +620,10 @@ struct RendererTriangleFill : RendererBase { const ImU32 Col; }; -template -struct RendererQuadFill : RendererBase { - RendererQuadFill(const _Getter& getter, ImU32 col) : RendererBase(getter.Count / 4, 6, 4), - Getter(getter), - Col(col) {} - void Init(ImDrawList3D& draw_list_3d) const { - UV = draw_list_3d._SharedData->TexUvWhitePixel; - } +template struct RendererQuadFill : RendererBase { + RendererQuadFill(const _Getter& getter, ImU32 col) : RendererBase(getter.Count / 4, 6, 4), Getter(getter), Col(col) {} + + void Init(ImDrawList3D& draw_list_3d) const { UV = draw_list_3d._SharedData->TexUvWhitePixel; } IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { ImPlot3DPoint p_plot[4]; @@ -637,8 +633,7 @@ struct RendererQuadFill : RendererBase { p_plot[3] = Getter(4 * prim + 3); // Check if the quad is outside the culling box - if (!cull_box.Contains(p_plot[0]) && !cull_box.Contains(p_plot[1]) && - !cull_box.Contains(p_plot[2]) && !cull_box.Contains(p_plot[3])) + if (!cull_box.Contains(p_plot[0]) && !cull_box.Contains(p_plot[1]) && !cull_box.Contains(p_plot[2]) && !cull_box.Contains(p_plot[3])) return false; // Project the quad vertices to screen space @@ -682,9 +677,10 @@ struct RendererQuadFill : RendererBase { draw_list_3d._IdxWritePtr += 6; - // Add depth values for the two triangles - draw_list_3d._ZWritePtr[0] = GetPointDepth((p_plot[0] + p_plot[1] + p_plot[2]) / 3.0f); - draw_list_3d._ZWritePtr[1] = GetPointDepth((p_plot[0] + p_plot[2] + p_plot[3]) / 3.0f); + // Add depth value for the quad + float z = GetPointDepth((p_plot[0] + p_plot[1] + p_plot[2] + p_plot[3]) / 4.0f); + draw_list_3d._ZWritePtr[0] = z; + draw_list_3d._ZWritePtr[1] = z; draw_list_3d._ZWritePtr += 2; // Update vertex count @@ -698,15 +694,93 @@ struct RendererQuadFill : RendererBase { const ImU32 Col; }; -template -struct RendererSurfaceFill : RendererBase { - RendererSurfaceFill(const _Getter& getter, int x_count, int y_count, ImU32 col, double scale_min, double scale_max) : RendererBase((x_count - 1) * (y_count - 1), 6, 4), - Getter(getter), - XCount(x_count), - YCount(y_count), - Col(col), - ScaleMin(scale_min), - ScaleMax(scale_max) {} +template struct RendererQuadImage : RendererBase { + RendererQuadImage(const _Getter& getter, ImTextureRef tex_ref, const ImVec2& uv0, const ImVec2& uv1, const ImVec2& uv2, const ImVec2& uv3, + ImU32 col) + : RendererBase(getter.Count / 4, 6, 4), Getter(getter), TexRef(tex_ref), UV0(uv0), UV1(uv1), UV2(uv2), UV3(uv3), Col(col) {} + + void Init(ImDrawList3D& draw_list_3d) const {} + + IMPLOT3D_INLINE bool Render(ImDrawList3D& draw_list_3d, const ImPlot3DBox& cull_box, int prim) const { + ImPlot3DPoint p_plot[4]; + p_plot[0] = Getter(4 * prim); + p_plot[1] = Getter(4 * prim + 1); + p_plot[2] = Getter(4 * prim + 2); + p_plot[3] = Getter(4 * prim + 3); + + // Check if the quad is outside the culling box + if (!cull_box.Contains(p_plot[0]) && !cull_box.Contains(p_plot[1]) && !cull_box.Contains(p_plot[2]) && !cull_box.Contains(p_plot[3])) + return false; + + // Set texture ID to be used when rendering this quad + draw_list_3d.SetTexture(TexRef); + + // Project the quad vertices to screen space + ImVec2 p[4]; + p[0] = PlotToPixels(p_plot[0]); + p[1] = PlotToPixels(p_plot[1]); + p[2] = PlotToPixels(p_plot[2]); + p[3] = PlotToPixels(p_plot[3]); + + // Add vertices for two triangles + draw_list_3d._VtxWritePtr[0].pos.x = p[0].x; + draw_list_3d._VtxWritePtr[0].pos.y = p[0].y; + draw_list_3d._VtxWritePtr[0].uv = UV0; + draw_list_3d._VtxWritePtr[0].col = Col; + + draw_list_3d._VtxWritePtr[1].pos.x = p[1].x; + draw_list_3d._VtxWritePtr[1].pos.y = p[1].y; + draw_list_3d._VtxWritePtr[1].uv = UV1; + draw_list_3d._VtxWritePtr[1].col = Col; + + draw_list_3d._VtxWritePtr[2].pos.x = p[2].x; + draw_list_3d._VtxWritePtr[2].pos.y = p[2].y; + draw_list_3d._VtxWritePtr[2].uv = UV2; + draw_list_3d._VtxWritePtr[2].col = Col; + + draw_list_3d._VtxWritePtr[3].pos.x = p[3].x; + draw_list_3d._VtxWritePtr[3].pos.y = p[3].y; + draw_list_3d._VtxWritePtr[3].uv = UV3; + draw_list_3d._VtxWritePtr[3].col = Col; + + draw_list_3d._VtxWritePtr += 4; + + // Add indices for two triangles + draw_list_3d._IdxWritePtr[0] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx); + draw_list_3d._IdxWritePtr[1] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 1); + draw_list_3d._IdxWritePtr[2] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 2); + + draw_list_3d._IdxWritePtr[3] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx); + draw_list_3d._IdxWritePtr[4] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 2); + draw_list_3d._IdxWritePtr[5] = (ImDrawIdx)(draw_list_3d._VtxCurrentIdx + 3); + + draw_list_3d._IdxWritePtr += 6; + + // Add depth value for the quad + float z = GetPointDepth((p_plot[0] + p_plot[1] + p_plot[2] + p_plot[3]) / 4.0f); + draw_list_3d._ZWritePtr[0] = z; + draw_list_3d._ZWritePtr[1] = z; + draw_list_3d._ZWritePtr += 2; + + // Update vertex count + draw_list_3d._VtxCurrentIdx += 4; + + // Reset texture ID + draw_list_3d.ResetTexture(); + + return true; + } + + const _Getter& Getter; + const ImTextureRef TexRef; + const ImVec2 UV0, UV1, UV2, UV3; + const ImU32 Col; +}; + +template struct RendererSurfaceFill : RendererBase { + RendererSurfaceFill(const _Getter& getter, int x_count, int y_count, ImU32 col, double scale_min, double scale_max) + : RendererBase((x_count - 1) * (y_count - 1), 6, 4), Getter(getter), XCount(x_count), YCount(y_count), Col(col), ScaleMin(scale_min), + ScaleMax(scale_max) {} void Init(ImDrawList3D& draw_list_3d) const { UV = draw_list_3d._SharedData->TexUvWhitePixel; @@ -735,8 +809,7 @@ struct RendererSurfaceFill : RendererBase { p_plot[3] = Getter(x + (y + 1) * XCount); // Check if the quad is outside the culling box - if (!cull_box.Contains(p_plot[0]) && !cull_box.Contains(p_plot[1]) && - !cull_box.Contains(p_plot[2]) && !cull_box.Contains(p_plot[3])) + if (!cull_box.Contains(p_plot[0]) && !cull_box.Contains(p_plot[1]) && !cull_box.Contains(p_plot[2]) && !cull_box.Contains(p_plot[3])) return false; // Compute colors @@ -824,27 +897,20 @@ struct RendererSurfaceFill : RendererBase { // [SECTION] Indexers //----------------------------------------------------------------------------- -template -IMPLOT3D_INLINE T IndexData(const T* data, int idx, int count, int offset, int stride) { +template IMPLOT3D_INLINE T IndexData(const T* data, int idx, int count, int offset, int stride) { const int s = ((offset == 0) << 0) | ((stride == sizeof(T)) << 1); switch (s) { case 3: return data[idx]; case 2: return data[(offset + idx) % count]; - case 1: return *(const T*)(const void*)((const unsigned char*)data + (size_t)((idx)) * stride); + case 1: return *(const T*)(const void*)((const unsigned char*)data + (size_t)((idx))*stride); case 0: return *(const T*)(const void*)((const unsigned char*)data + (size_t)((offset + idx) % count) * stride); default: return T(0); } } -template -struct IndexerIdx { - IndexerIdx(const T* data, int count, int offset = 0, int stride = sizeof(T)) : Data(data), - Count(count), - Offset(offset), - Stride(stride) {} - template IMPLOT3D_INLINE double operator()(I idx) const { - return (double)IndexData(Data, idx, Count, Offset, Stride); - } +template struct IndexerIdx { + IndexerIdx(const T* data, int count, int offset = 0, int stride = sizeof(T)) : Data(data), Count(count), Offset(offset), Stride(stride) {} + template IMPLOT3D_INLINE double operator()(I idx) const { return (double)IndexData(Data, idx, Count, Offset, Stride); } const T* Data; int Count; int Offset; @@ -855,8 +921,7 @@ struct IndexerIdx { // [SECTION] Getters //----------------------------------------------------------------------------- -template -struct GetterXYZ { +template struct GetterXYZ { GetterXYZ(_IndexerX x, _IndexerY y, _IndexerZ z, int count) : IndexerX(x), IndexerY(y), IndexerZ(z), Count(count) {} template IMPLOT3D_INLINE ImPlot3DPoint operator()(I idx) const { return ImPlot3DPoint((float)IndexerX(idx), (float)IndexerY(idx), (float)IndexerZ(idx)); @@ -867,8 +932,7 @@ struct GetterXYZ { const int Count; }; -template -struct GetterLoop { +template struct GetterLoop { GetterLoop(_Getter getter) : Getter(getter), Count(getter.Count + 1) {} template IMPLOT3D_INLINE ImPlot3DPoint operator()(I idx) const { idx = idx % (Count - 1); @@ -878,8 +942,7 @@ struct GetterLoop { const int Count; }; -template -struct GetterTriangleLines { +template struct GetterTriangleLines { GetterTriangleLines(_Getter getter) : Getter(getter), Count(getter.Count * 2) {} template IMPLOT3D_INLINE ImPlot3DPoint operator()(I idx) const { idx = ((idx % 6 + 1) / 2) % 3 + idx / 6 * 3; @@ -889,8 +952,7 @@ struct GetterTriangleLines { const int Count; }; -template -struct GetterQuadLines { +template struct GetterQuadLines { GetterQuadLines(_Getter getter) : Getter(getter), Count(getter.Count * 2) {} template IMPLOT3D_INLINE ImPlot3DPoint operator()(I idx) const { idx = ((idx % 8 + 1) / 2) % 4 + idx / 8 * 4; @@ -900,10 +962,8 @@ struct GetterQuadLines { const int Count; }; -template -struct GetterSurfaceLines { - GetterSurfaceLines(_Getter getter, int x_count, int y_count) - : Getter(getter), XCount(x_count), YCount(y_count) { +template struct GetterSurfaceLines { + GetterSurfaceLines(_Getter getter, int x_count, int y_count) : Getter(getter), XCount(x_count), YCount(y_count) { int horizontal_segments = (XCount - 1) * YCount; int vertical_segments = (YCount - 1) * XCount; int segments = horizontal_segments + vertical_segments; @@ -946,9 +1006,7 @@ struct GetterSurfaceLines { struct Getter3DPoints { Getter3DPoints(const ImPlot3DPoint* points, int count) : Points(points), Count(count) {} - template IMPLOT3D_INLINE ImPlot3DPoint operator()(I idx) const { - return Points[idx]; - } + template IMPLOT3D_INLINE ImPlot3DPoint operator()(I idx) const { return Points[idx]; } const ImPlot3DPoint* Points; const int Count; }; @@ -957,8 +1015,7 @@ struct GetterMeshTriangles { GetterMeshTriangles(const ImPlot3DPoint* vtx, const unsigned int* idx, int idx_count) : Vtx(vtx), Idx(idx), IdxCount(idx_count), TriCount(idx_count / 3), Count(idx_count) {} - template - IMPLOT3D_INLINE ImPlot3DPoint operator()(I i) const { + template IMPLOT3D_INLINE ImPlot3DPoint operator()(I i) const { unsigned int vi = Idx[i]; return Vtx[vi]; } @@ -975,8 +1032,7 @@ struct GetterMeshTriangles { //----------------------------------------------------------------------------- /// Renders primitive shapes -template